package org.jeecgframework.web.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.util.List;
import java.math.RoundingMode;
import java.net.MalformedURLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mybatis.ext.WiseCoreService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.model.json.*;
import org.jeecgframework.core.util.*;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.service.*;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;

/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 发货单信息
 * @date 2018-01-25 10:08:29
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsDelinerController")
public class CbsDelinerController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsDelinerController.class);

    @Autowired
    private CbsDelinerServiceI cbsDelinerService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private CbsDeliverEquipmentMapServiceI cbsDeliverEquipmentMapServiceI;
    @Autowired
    private ZyEquipmentTypeServiceI zyEquipmentTypeService;
    @Autowired
    private CbsReturnEquipmentServiceI cbsReturnEquipmentServiceI;

    @Autowired
    private ZyEquipmentSpareServiceI zyEquipmentSpareService;
    @Autowired
    private CbsServiceLogServiceI cbsServiceLogServiceI;
    @Autowired
    private ZyEsItemServiceI zyEsItemService;
    @Autowired
    private CbsDeliverEquipmentServiceI cbsDeliverEquipmentService;
    @Autowired
    private CbsReturnEquipmentDetailServiceI cbsReturnEquipmentDetailServiceI;

    @Autowired
    private WiseCoreService wiseCoreService;

    @Autowired
    private WxCommonService wxCommonService;
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }


    /**
     * 发货单信息列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsDeliner")
    public ModelAndView cbsDeliner(HttpServletRequest request) {
        //获取登录的用户信息
        TSUser user = ResourceUtil.getSessionUserName();

        //用户的角色集合
        List<String> roleList = new ArrayList<>();
        List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSUser.id='" + user.getId() + "'");
        for (TSRoleUser tsRoleUser : tsRoleUserList) {
            String role = tsRoleUser.getTSRole().getRoleCode();
            roleList.add(role);
        }
        //判断登录用户身份
        if (roleList.contains("logistics")) {
            return new ModelAndView("com/zybk/cbs_deliver/cbsDelinerList-logistics");
        }
        if (roleList.contains("barcoCSA") || roleList.contains("admin")) {
            return new ModelAndView("com/zybk/cbs_deliver/cbsDelinerList");
        } else {
            return new ModelAndView("com/zybk/cbs_deliver/cbsDelinerList");
        }
    }

    /**
     * 物流发货单待办信息列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsDelinerTodo")
    public ModelAndView cbsDelinerTodo(HttpServletRequest request) {
        //return new ModelAndView("com/zybk/cbs_deliver_equipment/cbsDeliverEquipmentList");
//		return new ModelAndView("com/zybk/cbs_deliver/cbsDelinerList");
//		return new ModelAndView("com/zybk/cbs_deliver/cbsDelinerList");

        //return new ModelAndView("com/zybk/cbs_deliver_equipment/cbsDeliverEquipmentList");
        //获取登录的用户信息
        TSUser user = ResourceUtil.getSessionUserName();

        //用户的角色集合
        List<String> roleList = new ArrayList<>();
        List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSUser.id='" + user.getId() + "'");
        for (TSRoleUser tsRoleUser : tsRoleUserList) {
            String role = tsRoleUser.getTSRole().getRoleCode();
            roleList.add(role);
        }
        //判断登录用户身份
        if (roleList.contains("logistics")) {
            if (StringUtil.isNotEmpty(request.getParameter("type")) && request.getParameter("type").equals("wlYfhTodo")) {
                return new ModelAndView("com/zybk/cbs_deliver/cbsDelinerList-logisticsWlyfhTodo");
            } else {
                return new ModelAndView("com/zybk/cbs_deliver/cbsDelinerList-logisticsTodo");
            }
        } else {
            return null;
        }
    }

    /**
     * CSA发货单待办信息列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsCSADelinerTodo")
    public ModelAndView cbsCSADelinerTodo(HttpServletRequest request) {
        //return new ModelAndView("com/zybk/cbs_deliver_equipment/cbsDeliverEquipmentList");
//		return new ModelAndView("com/zybk/cbs_deliver/cbsDelinerList");
//		return new ModelAndView("com/zybk/cbs_deliver/cbsDelinerList");

        //return new ModelAndView("com/zybk/cbs_deliver_equipment/cbsDeliverEquipmentList");
        //获取登录的用户信息
        TSUser user = ResourceUtil.getSessionUserName();

        //用户的角色集合
        List<String> roleList = new ArrayList<>();
        List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSUser.id='" + user.getId() + "'");
        for (TSRoleUser tsRoleUser : tsRoleUserList) {
            String role = tsRoleUser.getTSRole().getRoleCode();
            roleList.add(role);
        }
        //判断登录用户身份
        if (roleList.contains("barcoCSA")) {
            return new ModelAndView("com/zybk/cbs_deliver/cbsDelinerList-CSATodo");
        } else {
            return null;
        }
    }

    /**
     * CSA发货跳转
     *
     * @return
     */
    @RequestMapping(params = "CSADeliner")
    public ModelAndView CSADeliner(HttpServletRequest request) {
        List<String> stringList = new ArrayList<>();
        String id1 = request.getParameter("id");
        if (id1 != null && id1 != "") {
            CbsDelinerEntity entity = systemService.singleResult("from CbsDelinerEntity where id = '" + id1 + "'");
            List<CbsServiceEntity> cbsServiceEntityList = systemService.findHql("FROM CbsServiceEntity where code = '" + entity.getCrCode() + "'");
            if (cbsServiceEntityList!=null && cbsServiceEntityList.size() > 0) {
            	request.setAttribute("servicetype", cbsServiceEntityList.get(0).getServiceType2().getName());
            }
            List<CbsDeliverEquipmentEntity> cbsDeliverEquipmentEntityList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + id1 + "'");

            int isReturnCount = 0;
            for (int i = 0; i < cbsDeliverEquipmentEntityList.size(); i++) {
                CbsDeliverEquipmentEntity cbsDeliverEquipmentEntity = cbsDeliverEquipmentEntityList.get(i);

                stringList.add(cbsDeliverEquipmentEntity.getId());
                if (StringUtil.isNotEmpty(cbsDeliverEquipmentEntity) && StringUtil.isNotEmpty(cbsDeliverEquipmentEntity.getIsReturn())) {
                    if (cbsDeliverEquipmentEntity.getIsReturn() == 2) {
                        isReturnCount++;
                    }
                }


            }
            request.setAttribute("stringList", stringList);
            request.setAttribute("isReturnCount", isReturnCount);
            request.setAttribute("cbsDeliverEquipmentEntityList", cbsDeliverEquipmentEntityList);
            if (entity.getShi() != null) {
                List<CbsWarehouseEntity> CbsWarehouseEntitys = systemService.findHql("from CbsWarehouseEntity where shi.id='" + entity.getShi().getId() + "' and isClose='0'");
                if (CbsWarehouseEntitys.size() > 0) {
                    if (CbsWarehouseEntitys.get(0).getName() != null) {
                        request.setAttribute("warehouseName", CbsWarehouseEntitys.get(0).getName());
                    }

                }
            }
            if (entity.getDeliverLogistics() != null && !entity.getDeliverLogistics().equals("")) {
                String sql = "SELECT\n" +
                        "\tcw.name as name,\n" +
                        "\tcw.id as id,cw.user_name AS userName,cw.phone AS phone,cw.email AS email\n" +
                        "FROM\n" +
                        "\tcbs_warehouse cw\n" +
                        "WHERE\n" +
                        "\tcw.is_close = '0'\n" +
                        "and cw.logistics = '" + entity.getDeliverLogistics() + "'\n";
                List<Map<String, Object>> wareList = systemService.findForJdbc(sql);
                request.setAttribute("wareList", wareList);
            } else {
                List<Map<String, Object>> wareList = systemService.findForJdbc("select cw.name as name,cw.id as id from cbs_warehouse cw");
                request.setAttribute("wareList", wareList);
            }
            List<TSTerritory> territoryList = null;
            String hql = "from CbsDelinerEntity where id ='" + id1 + "'";
            CbsDelinerEntity cbsDelinerEntity = systemService.singleResult(hql);
            request.setAttribute("cbsDelinerEntity", cbsDelinerEntity);
            if (cbsDelinerEntity.getShi() != null) {
                List<CbsWarehouseEntity> cbsWarehouseEntityList = systemService.findHql("from CbsWarehouseEntity where shi.id='" + cbsDelinerEntity.getShi().getId() + "' and isClose='0' ");
                if (cbsWarehouseEntityList != null && cbsWarehouseEntityList.size() > 0) {
                    request.setAttribute("cbsWarehouseEntityList", cbsWarehouseEntityList.get(0).getLogistics());
                }
            }
            territoryList = systemService.findHql("from TSTerritory where territoryLevel = 1 order by territorySort");
            request.setAttribute("territoryList", territoryList);
            if (cbsDelinerEntity.getShi() != null) {
                List<CbsWarehouseEntity> cbsWarehouseEntityList1 = systemService.findHql("from CbsWarehouseEntity where shi.id='" + cbsDelinerEntity.getShi().getId() + "' and isClose='0'");
                if (cbsWarehouseEntityList1.size() > 0) {
                    request.setAttribute("cbsWarehouseEntity", cbsWarehouseEntityList1.get(0));
                }
            }
            //获取提货省下面的所有城市
            if (entity.getThSheng() != null) {
                List<TSTerritory> cityList = systemService.findHql("from TSTerritory where territoryLevel=2 and TSTerritory.id='" + entity.getThSheng().getId() + "'");
                request.setAttribute("cityList", cityList);
            }


            //根据返件物流获取对应的联系人
            TSDepart tsDepart2 = systemService.singleResult("from TSDepart where departname='" + entity.getReturnLogistics() + "' and orgType='logistics'");
            if (tsDepart2 != null) {
                List<ZyContactsEntity> returnContacts = systemService.findHql("from ZyContactsEntity where belongOrg.id='" + tsDepart2.getId() + "'");
                if (returnContacts != null && returnContacts.size() > 0) {
                    request.setAttribute("returnContacts", returnContacts.get(0));
                } else {
                    request.setAttribute("returnContacts", null);
                }

            }

        }
        List<TSType> types = systemService.findHql("from TSType where TSTypegroup.typegroupcode='kuwei'");
        request.setAttribute("types", types);
        List<TSType> fhSLAs = systemService.findHql("from TSType where TSTypegroup.typegroupcode='fhSLA'");
        request.setAttribute("fhSLAs", fhSLAs);

        //查询物流
        String hql = "from TSDepart where orgType='logistics' and logicDelete = '0'";
        List<TSDepart> tsDepartList = systemService.findHql(hql);
        request.setAttribute("tsDepartList", tsDepartList);
        
        //获取所有的发货单类型
        String hql2 = "from TSType where TSTypegroup.typegroupcode='Deliver_Type'";
        List<TSType> deliverTypeList = systemService.findHql(hql2);
        request.setAttribute("deliverTypeList", deliverTypeList);

        return new ModelAndView("com/zybk/cbs_deliver/CSAdeliver");
    }

    @ResponseBody
    @RequestMapping(params = "getSLA")
    public AjaxJson getSLA(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String logistics = request.getParameter("logisticsName");
        String cityId = request.getParameter("cityId");
        try {

//            String hql = "from CbsWarehouseEntity where shi.id='" + cityId + "' and logistics = '" + logistics + "'";
//            List<CbsWarehouseEntity> cbsWarehouseEntityList = systemService.findHql(hql);
//            String sql = "from CbsWarehouseSlaEntity where cbsWarehouseId.id= '" + cbsWarehouseEntityList.get(0).getId() + "' ORDER BY slaType DESC";
//            List<CbsWarehouseSlaEntity> cbsWarehouseSlaEntityList = systemService.findHql(sql);
            List<Map<String, Object>> cbsWarehouseSlaEntityList = systemService.findForJdbc("SELECT\n" +
                    "\tw.id AS id,\n" +
                    "\tw.`name` AS `name`,\n" +
                    "\tw.logistics AS logistics,\n" +
                    "\ts.is_priority AS isPriority,\n" +
                    "\tCASE\n" +
                    "WHEN s.sla_type = '1' THEN\n" +
                    "\t'SL1'\n" +
                    "WHEN s.sla_type = '2' THEN\n" +
                    "\t'SL2'\n" +
                    "WHEN s.sla_type = '3' THEN\n" +
                    "\t'SL3'\n" +
                    "WHEN s.sla_type = '4' THEN\n" +
                    "\t'SL4'\n" +
                    "ELSE\n" +
                    "\t'无'\n" +
                    "END AS slaType\n" +
                    "FROM\n" +
                    "\tcbs_warehouse w\n" +
                    "LEFT JOIN cbs_warehouse_sla s ON w.id = s.cbs_warehouse_id\n" +
                    "WHERE\n" +
                    "\ts.shi = '" + cityId + "'\n" +
                    "AND w.logistics = '" + logistics + "' and s.is_priority = '1'");
            ajaxJson.setObj(cbsWarehouseSlaEntityList.get(0));
        } catch (Exception e) {
            e.getMessage();
        }
        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "getSLAByWarouse")
    public AjaxJson getSLAByWarouse(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String logistics = request.getParameter("logisticsName");
        String cityId = request.getParameter("cityId");
        String waresoueId = request.getParameter("deliverWarehouseId");
        try {

//            String hql = "from CbsWarehouseEntity where shi.id='" + cityId + "' and logistics = '" + logistics + "'";
//            List<CbsWarehouseEntity> cbsWarehouseEntityList = systemService.findHql(hql);
//            String sql = "from CbsWarehouseSlaEntity where cbsWarehouseId.id= '" + cbsWarehouseEntityList.get(0).getId() + "' ORDER BY slaType DESC";
//            List<CbsWarehouseSlaEntity> cbsWarehouseSlaEntityList = systemService.findHql(sql);
            List<Map<String, Object>> cbsWarehouseSlaEntityList = systemService.findForJdbc("SELECT\n" +
                    "\tw.id AS id,\n" +
                    "\tw.`name` AS `name`,\n" +
                    "\tw.logistics AS logistics,\n" +
                    "\ts.is_priority AS isPriority,\n" +
                    "\tCASE\n" +
                    "WHEN s.sla_type = '1' THEN\n" +
                    "\t'SL1'\n" +
                    "WHEN s.sla_type = '2' THEN\n" +
                    "\t'SL2'\n" +
                    "WHEN s.sla_type = '3' THEN\n" +
                    "\t'SL3'\n" +
                    "WHEN s.sla_type = '4' THEN\n" +
                    "\t'SL4'\n" +
                    "ELSE\n" +
                    "\t'无'\n" +
                    "END AS slaType\n" +
                    "FROM\n" +
                    "\tcbs_warehouse w\n" +
                    "LEFT JOIN cbs_warehouse_sla s ON w.id = s.cbs_warehouse_id\n" +
                    "WHERE\n" +
                    "\ts.shi = '" + cityId + "'\n" +
                    "AND w.logistics = '" + logistics + "'" +
                    "AND w.`id` = '" + waresoueId + "'");
            ajaxJson.setObj(cbsWarehouseSlaEntityList.get(0));
        } catch (Exception e) {
            e.getMessage();
        }
        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "getSLABy")
    public AjaxJson getSLABy(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String slaId = request.getParameter("slaId");
        try {

            String hql = "from CbsWarehouseSlaEntity where id = '" + slaId + "'";
            CbsWarehouseSlaEntity cbsWarehouseSlaEntity = systemService.singleResult(hql);
            ajaxJson.setObj(cbsWarehouseSlaEntity);
        } catch (Exception e) {
            e.getMessage();
        }
        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "getIsReturnByItem")
    public AjaxJson getIsReturnByItem(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = request.getParameter("id");
        try {
            ZyEsItemEntity item = systemService.get(ZyEsItemEntity.class, id);
            ajaxJson.setObj(item);
        } catch (Exception e) {
            e.getMessage();
        }
        return ajaxJson;
    }


    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */


    @RequestMapping(params = "datagrid")
    public void datagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();

        // add start 181203 Amy 所有条件为空时，检索欠货中和CSA待发货的
        boolean flag = false; //页面查询条件是否为空
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
            if (   key.equals("code") || key.equals("deliverType") || key.equals("status") ||
                    key.equals("soCode") || key.equals("srCode") ||
                    key.equals("cinemaName") || key.equals("applyreason") ||
                    key.equals("crCode") || key.equals("fhSLA") ||
                    key.equals("phone") || key.equals("CSAName") ||
                    key.equals("recordId") || key.equals("deliverLogistics") ||
                    key.equals("_territoryL2") || key.equals("_territoryL3") ||
                    key.equals("logNumber") || key.equals("signStandard") ||
                    key.equals("etaStandard") || key.equals("isStandard") ||
                    key.equals("CSASendTime_begin") || key.equals("CSASendTime_end") ||
                    key.equals("createDate_begin") || key.equals("createDate_end") ||
                    key.equals("logisticsSendTime_begin") || key.equals("logisticsSendTime_end") || 
                    key.equals("isReturn") || key.equals("dept")) {
                if (!StringUtil.isEmpty(parameterMap.get(key)[0])) {
                    flag = true;//页面 查询条件为空不做查询
                    break;
                }
            }
        }
        if (flag) {     
        // add end 181203
	        for (Object key : request.getParameterMap().keySet()) {
	            if ((String[]) request.getParameterMap().get(key) != null) {
	                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
	                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
	                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
	                    }
	                }
	            }
	        }
	
	        if (StringUtil.isNotEmpty(request.getParameter("logisticsSendTime_end"))) {
	            String logisticsSendTime_end = request.getParameter("logisticsSendTime_end") + " 23:59:59";
	            param.put("logisticsSendTime_end", logisticsSendTime_end);
	        }
	        if (StringUtil.isNotEmpty(request.getParameter("CSASendTime_end"))) {
	            String CSASendTime_end = request.getParameter("CSASendTime_end") + " 23:59:59";
	            param.put("CSASendTime_end", CSASendTime_end);
	        }
	        if (StringUtil.isNotEmpty(request.getParameter("createDate_end"))) {
	            String createDate_end = request.getParameter("createDate_end") + " 23:59:59";
	            param.put("createDate_end", createDate_end);
	        }
	        wiseCoreService.selectDataGrid("selectDeliverDatagrid", param, dataGrid);
        } else {
            // add start 181203 Amy 所有条件为空时，检索欠货中和CSA待发货的
        	//检索欠货中和CSA待发货的
        	List<String> statusList = new ArrayList<>();
        	statusList.add(StaticValue.CSAdfh);
        	statusList.add(StaticValue.qh);
        	param.put("statusList",statusList);
	        wiseCoreService.selectDataGrid("selectDeliverDatagrid", param, dataGrid);
	        // add end 181203
        }
        TagUtil.datagrid(response, dataGrid);
    }

    /*
     * 物流发货列表
     */
    @RequestMapping(params = "userDatagrid")
    public void userDatagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();
        TSUser user = ResourceUtil.getSessionUserName();
        String logisticsName = user.getCurrentDepart().getDepartname();
        System.out.println("logisticsName:" + logisticsName);
        param.put("logisticsName", logisticsName);

        // add start 190506 Amy 所有条件为空时，检索物流待处理的
        boolean flag = false; //页面查询条件是否为空
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
            if (   key.equals("code") || key.equals("status") ||
                    key.equals("crCode") || key.equals("soCode") ||
                    key.equals("srCode") || key.equals("cinemaName") ||
                    key.equals("_territoryL2") || key.equals("_territoryL3") ||
                    key.equals("fhSLA") || key.equals("isStandard") ||
                    key.equals("etaStandard") || key.equals("signStandard") ||
                    key.equals("logNumber") || key.equals("phone") ||
                    key.equals("CSASendTime_begin") || key.equals("CSASendTime_end") ||
                    key.equals("logisticsSendTime_begin") || key.equals("logisticsSendTime_end") ||
                    key.equals("getTime_begin") || key.equals("getTime_end")) {
                if (!StringUtil.isEmpty(parameterMap.get(key)[0])) {
                    flag = true;//页面 查询条件为空不做查询
                    break;
                }
            }
        }
        // add end 190506
        
        if (flag) {
	        for (Object key : request.getParameterMap().keySet()) {
	            if ((String[]) request.getParameterMap().get(key) != null) {
	                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
	                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
	                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
	                    }
	                }
	            }
	        }
	
	
	        if (StringUtil.isNotEmpty(request.getParameter("logisticsSendTime_end"))) {
	            String logisticsSendTime_end = request.getParameter("logisticsSendTime_end") + " 23:59:59";
	            param.put("logisticsSendTime_end", logisticsSendTime_end);
	        }
	        if (StringUtil.isNotEmpty(request.getParameter("CSASendTime_end"))) {
	            String CSASendTime_end = request.getParameter("CSASendTime_end") + " 23:59:59";
	            param.put("CSASendTime_end", CSASendTime_end);
	        }
	        if (StringUtil.isNotEmpty(request.getParameter("getTime_end"))) {
	            String getTime_end = request.getParameter("getTime_end") + " 23:59:59";
	            param.put("getTime_end", getTime_end);
	        }
        } else {
        	param.put("status", StaticValue.wldfh1);
        }
        wiseCoreService.selectDataGrid("selectDeliverForLogisticsDatagrid", param, dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }

    /*物流发货待办列表*/
    @RequestMapping(params = "userDatagridTodo")
    public void userDatagridTodo(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();

        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i]);
                    }
                }
            }
        }
        TSUser user = ResourceUtil.getSessionUserName();
        String logisticsName = user.getCurrentDepart().getDepartname();
        param.put("logisticsName", logisticsName);
        String departname = user.getCurrentDepart().getDepartname();
        param.put("departname", departname);


        if (StringUtil.isNotEmpty(request.getParameter("logisticsSendTime_end"))) {
            String logisticsSendTime_end = request.getParameter("logisticsSendTime_end") + " 23:59:59";
            param.put("logisticsSendTime_end", logisticsSendTime_end);
        }
        if (StringUtil.isNotEmpty(request.getParameter("CSASendTime_end"))) {
            String CSASendTime_end = request.getParameter("CSASendTime_end") + " 23:59:59";
            param.put("CSASendTime_end", CSASendTime_end);
        }
        if (StringUtil.isNotEmpty(request.getParameter("getTime_end"))) {
            String getTime_end = request.getParameter("getTime_end") + " 23:59:59";
            param.put("getTime_end", getTime_end);
        }
        wiseCoreService.selectDataGrid("selectDeliverForLogisticsTodoDatagrid", param, dataGrid);

        TagUtil.datagrid(response, dataGrid);
    }

    /*物流待签收待办列表*/
    @RequestMapping(params = "userDatagridWldqsTodo")
    public void userDatagridWldqsTodo(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();
        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i]);
                    }
                }
            }
        }
        TSUser user = ResourceUtil.getSessionUserName();
        String logisticsName = user.getCurrentDepart().getDepartname();
        param.put("logisticsName", logisticsName);
        String departname = user.getCurrentDepart().getDepartname();
        param.put("departname", departname);


        if (StringUtil.isNotEmpty(request.getParameter("logisticsSendTime_end"))) {
            String logisticsSendTime_end = request.getParameter("logisticsSendTime_end") + " 23:59:59";
            param.put("logisticsSendTime_end", logisticsSendTime_end);
        }
        if (StringUtil.isNotEmpty(request.getParameter("CSASendTime_end"))) {
            String CSASendTime_end = request.getParameter("CSASendTime_end") + " 23:59:59";
            param.put("CSASendTime_end", CSASendTime_end);
        }
        if (StringUtil.isNotEmpty(request.getParameter("getTime_end"))) {
            String getTime_end = request.getParameter("getTime_end") + " 23:59:59";
            param.put("getTime_end", getTime_end);
        }
        wiseCoreService.selectDataGrid("selectLogisticsWldqsTodoDatagrid", param, dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }

    /*CSA发货单待办列表*/
    @RequestMapping(params = "userCSADatagridTodo")
    public void userCSADatagridTodo(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();

        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i]);
                    }
                }
            }
        }
        if (StringUtil.isNotEmpty(request.getParameter("logisticsSendTime_end"))) {
            String logisticsSendTime_end = request.getParameter("logisticsSendTime_end") + " 23:59:59";
            param.put("logisticsSendTime_end", logisticsSendTime_end);
        }
        if (StringUtil.isNotEmpty(request.getParameter("CSASendTime_end"))) {
            String CSASendTime_end = request.getParameter("CSASendTime_end") + " 23:59:59";
            param.put("CSASendTime_end", CSASendTime_end);
        }
        if (StringUtil.isNotEmpty(request.getParameter("createDate_end"))) {
            String createDate_end = request.getParameter("createDate_end") + " 23:59:59";
            param.put("createDate_end", createDate_end);
        }
        wiseCoreService.selectDataGrid("selectDeliverForCSATodoDatagrid", param, dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 发货单信息新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(CbsDelinerEntity cbsDeliner, HttpServletRequest req) {
		/*if (StringUtil.isNotEmpty(cbsDeliner.getId())) {
			cbsDeliner = cbsDelinerService.getEntity(CbsDelinerEntity.class, cbsDeliner.getId());
			req.setAttribute("cbsDelinerPage", cbsDeliner);
		}*/
        //查询所有备件型号
        List<ZyEquipmentTypeEntity> equipmentTypeList = new ArrayList<ZyEquipmentTypeEntity>();
        List<ZyEquipmentTypeEntity> list = systemService.findHql("from ZyEquipmentTypeEntity");
        for (ZyEquipmentTypeEntity et : list) {
            List<ZyEquipmentTypeEntity> list2 = zyEquipmentTypeService.findHql("from ZyEquipmentTypeEntity where equipmentType.id='" + et.getId() + "'");
            if (list2.size() <= 0) {
                equipmentTypeList.add(et);
            }
        }
        String hql1 = "from TSDepart where orgType='logistics' and logicDelete = '0'";
        List<TSDepart> tsDepartList = systemService.findHql(hql1);
        req.setAttribute("tsDepartList", tsDepartList);
        req.setAttribute("equipmentTypeList", equipmentTypeList);
        String hql = "from TSType where TSTypegroup.typegroupcode='fhSLA'";
        List<TSType> tSTypeList = systemService.findHql(hql);
        req.setAttribute("tSTypeList", tSTypeList);
        List<CbsWarehouseEntity> cbsWarehouseEntityList = systemService.findHql("from CbsWarehouseEntity where isClose = '0'");
        req.setAttribute("cbsWarehouseEntityList", cbsWarehouseEntityList);
        return new ModelAndView("com/zybk/cbs_deliver/cbsDeliner-add");
    }


    /**
     * @param request
     * @return
     * @author xiul
     * 2018-1-22 上午12:00:42
     * Description 设备item - 选择设备类型，单选
     */
    @RequestMapping(params = "goChooseEquipmentType")
    public ModelAndView goChooseEquipmentType(HttpServletRequest request) {
        String uuid = request.getParameter("uuid");
        String id = request.getParameter("id");
        request.setAttribute("uuid", uuid);
        request.setAttribute("id", id);
        ZyEquipmentTypeEntity eqtype = systemService.singleResult("from ZyEquipmentTypeEntity where typeDesc='未知备件'");
        if (eqtype != null) {
            request.setAttribute("wuId", eqtype.getId());
        }

        if (StringUtil.isNotEmpty(id)) {

        }
        return new ModelAndView("com/zybk/cbs_deliver/CbsChooseEquipmentType");
    }

    /**
     * @param zyEquipmentTypeEntity
     * @param request
     * @param response
     * @param
     * @author xiul
     * 2018-1-22 上午12:00:42
     * Description 设备item - 选择设备类型datagrid加载
     */
    @RequestMapping(params = "dataGridOfChooseEquipmentType")
    @ResponseBody
    public List<TreeGrid> dataGridOfChooseEquipmentType(ZyEquipmentTypeEntity zyEquipmentTypeEntity, HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
        CriteriaQuery cq;
        List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
        cq = new CriteriaQuery(ZyEquipmentTypeEntity.class);
        cq.notEq("typeDesc", "设备");
        if (treegrid.getId() != null) {
            cq.eq("equipmentType.id", treegrid.getId());
        } else if (treegrid.getId() == null) {
            cq.isNull("equipmentType.id");
        }
        cq.add();
        cq.addOrder("typeDesc", SortDirection.asc);
        List<ZyEquipmentTypeEntity> ZyEquipmentTypeList = systemService.getListByCriteriaQuery(cq, false);
        TreeGridModel treeGridModel = new TreeGridModel();
        treeGridModel.setIdField("id");
        treeGridModel.setTextField("typeDesc");
        treeGridModel.setParentId("equipmentType_id");
        treeGridModel.setParentText("equipmentType_typeDesc");
        treeGridModel.setSrc("");
        treeGridModel.setChildList("childEquipmentTypes");
        treeGrids = systemService.treegrid(ZyEquipmentTypeList, treeGridModel);
        return treeGrids;
    }

    @RequestMapping(params = "getUuid")
    @ResponseBody
    public String getUuid() {
        return cbsDelinerService.getUuid();
    }


    /*
     * 查询所有备件类型
     * */
    @ResponseBody
    @RequestMapping(params = "getAllTypes")
    public AjaxJson getAllTypes(HttpServletRequest request) {
        System.out.println("查询所有备件类型");
        AjaxJson j = new AjaxJson();
        List<ZyEquipmentTypeEntity> equipmentTypeList = new ArrayList<ZyEquipmentTypeEntity>();
        List<ZyEquipmentTypeEntity> list = systemService.findHql("from ZyEquipmentTypeEntity");
        for (ZyEquipmentTypeEntity et : list) {
            List<ZyEquipmentTypeEntity> list2 = zyEquipmentTypeService.findHql("from ZyEquipmentTypeEntity where equipmentType.id='" + et.getId() + "'");
            if (list2.size() <= 0) {
                equipmentTypeList.add(et);
            }
        }
        System.out.println(equipmentTypeList.size());
        j.setObj(equipmentTypeList);
        return j;
    }

    /*
     * 查询备件号
     * */
    @ResponseBody
    @RequestMapping(params = "getItemId")
    public List<ZyEsItemEntity> getItem(HttpServletRequest request) {
        String id = request.getParameter("id");
        System.out.println(id);
        List<ZyEsItemEntity> ItemList = systemService.findHql("from ZyEsItemEntity where type.id='" + id + "' order by item");
        return ItemList;
    }


    /*
     * 查询仓库信息
     * */
    @ResponseBody
    @RequestMapping(params = "getWarehouse")
    public AjaxJson getWarehouse(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String territoryId = request.getParameter("code");

        String sql = "SELECT\n" +
                "\tcw.name as name,\n" +
                "\tcw.id as id\n" +
                "FROM\n" +
                "\tcbs_warehouse cw\n" +
                "LEFT JOIN cbs_warehouse_sla cws ON cws.cbs_warehouse_id = cw.id\n" +
                "WHERE\n" +
                "\tcw.is_close = '0'\n" +
                "AND cws.shi='" + territoryId + "'";
        List<Map<String, Object>> wareList = systemService.findForJdbc(sql);
        String hql = "from CbsWarehouseEntity where shi.id=?";
        List<CbsWarehouseEntity> cbsWarehouseList = systemService.findHql(hql, territoryId);

        System.out.println("cbsWarehouseList:" + cbsWarehouseList);
        j.setObj(wareList);
        return j;
    }


    /*
     * 获取服务单号
     * */
    @RequestMapping(params = "getServiceCode")
    @ResponseBody
    public AjaxJson getServiceCode() {
        AjaxJson j = new AjaxJson();

        String hql = " from CbsServiceEntity";
        List<CbsServiceEntity> cbsServiceList = systemService.findHql(hql);
        j.setObj(cbsServiceList);
        return j;
    }

    /*
     * 获取物流信息
     * */
    @RequestMapping(params = "getLogistics")
    @ResponseBody
    public AjaxJson getLogistics() {
        AjaxJson j = new AjaxJson();
        String hql = "from TSDepart where orgType='logistics' and logicDelete = '0'";
        List<TSDepart> tsDepartList = systemService.findHql(hql);
        j.setObj(tsDepartList);
        return j;
    }

    /**
     * 取消返件，跳转取消原因页面
     */
    @RequestMapping(params = "goCancelTheShipment")
    public ModelAndView goCancelTheShipment(HttpServletRequest request) {
        String id = request.getParameter("id");
        request.setAttribute("id", id);
        CbsReturnEquipmentEntity cbsReturnEquipmentEntity = systemService.getEntity(CbsReturnEquipmentEntity.class, id);
        request.setAttribute("code", StringUtil.isNotEmpty(cbsReturnEquipmentEntity.getCode()) ? cbsReturnEquipmentEntity.getCode() : "");
        return new ModelAndView("com/zybk/cbs_return_equipment/cbsReturnEquipmentCandelDes");
    }

    /**
     * 取消发货，跳转取消原因页面
     */
    @RequestMapping(params = "goCancelDeliver")
    public ModelAndView goCancelDeliver(HttpServletRequest request) {
        String id = request.getParameter("id");
        String code = request.getParameter("code");
        request.setAttribute("id", id);
        request.setAttribute("code", code);
        return new ModelAndView("com/zybk/cbs_deliver/cancelDeliver");
    }

    /*
     * 获取物流信息
     * */
    @RequestMapping(params = "getLogisticsForCity")
    @ResponseBody
    public AjaxJson getLogisticsForCity() {
        AjaxJson j = new AjaxJson();
        String hql = "from TSDepart where orgType='logistics'";
        List<TSDepart> tsDepartList = systemService.findHql(hql);
        j.setObj(tsDepartList);
        return j;
    }

    /*
     * 获取发货单类型
     * */
    @RequestMapping(params = "getDeliverType")
    @ResponseBody
    public AjaxJson getDeliverType() {
        //System.out.println("执行了.............");
        AjaxJson j = new AjaxJson();
        String hql = "from TSType where TSTypegroup.typegroupcode='Deliver_Type'";
        List<TSType> tSTypeList = systemService.findHql(hql);
        System.out.println("tSTypeList:" + tSTypeList);
        j.setObj(tSTypeList);
        return j;
    }

    /*
     * 发货SLA
     * */
    @RequestMapping(params = "getSendSLA")
    @ResponseBody
    public AjaxJson getSendSLA() {
        //System.out.println("执行了.............");
        AjaxJson j = new AjaxJson();
        String hql = "from TSType where TSTypegroup.typegroupcode='fhSLA'";
        List<TSType> tSTypeList = systemService.findHql(hql);
        System.out.println("tSTypeList:" + tSTypeList);
        j.setObj(tSTypeList);
        return j;
    }

    /*
     * 库位
     * */
    @RequestMapping(params = "getKuWei")
    @ResponseBody
    public AjaxJson getKuWei() {
        //System.out.println("执行了.............");
        AjaxJson j = new AjaxJson();
        String hql = "from TSType where TSTypegroup.typegroupcode='kuwei'";
        List<TSType> tSTypeList = systemService.findHql(hql);
        System.out.println("tSTypeList:" + tSTypeList);
        j.setObj(tSTypeList);
        return j;
    }

    /*
     * 根据收货地址城市选择推荐物流
     * */
    @RequestMapping(params = "getLogisticsByCity")
    @ResponseBody
    public AjaxJson getLogisticsByCity(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String code = request.getParameter("code");
        List<Map<String, Object>> cbsWarehouseSlaListes = systemService.findForJdbc("SELECT\n" +
                "\tw.id AS id,\n" +
                "\tw.`name` AS `name`,w.phone AS phone,w.email AS email,w.user_name AS userName,\n" +
                "\tw.logistics AS logistics,\n" +
                "\ts.is_priority AS isPriority,\n" +
                "\tCASE\n" +
                "WHEN s.sla_type = '1' THEN\n" +
                "\t'SL1'\n" +
                "WHEN s.sla_type = '2' THEN\n" +
                "\t'SL2'\n" +
                "WHEN s.sla_type = '3' THEN\n" +
                "\t'SL3'\n" +
                "WHEN s.sla_type = '4' THEN\n" +
                "\t'SL4'\n" +
                "ELSE\n" +
                "\t'无'\n" +
                "END AS slaType\n" +
                "FROM\n" +
                "\tcbs_warehouse w\n" +
                "LEFT JOIN cbs_warehouse_sla s ON w.id = s.cbs_warehouse_id\n" +
                "WHERE\n" +
                "\ts.shi = '" + code + "'\n" +
                "AND s.is_priority = '1'\n" +
                "ORDER BY s.sla_type DESC");
        j.setObj(cbsWarehouseSlaListes);
        return j;
    }

    /*
     * 根据发货物流和收货地址所在城市选择仓库
     * */
    @RequestMapping(params = "getWarehouseByCity")
    @ResponseBody
    public AjaxJson getWarehouseByCity(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String cityCode = request.getParameter("cityCode");
//        String hql = "from CbsWarehouseEntity where isClose='0' and shi.id='" + cityCode + "'";
//        List<CbsWarehouseEntity> cbsWarehouseList = systemService.findHql(hql);
        List<Map<String, Object>> cbsWarehouseList = systemService.findForJdbc("SELECT\n" +
                "\tw.id as id,w.`name` as `name` ,w.logistics as logistics\n" +
                "FROM\n" +
                "\tcbs_warehouse w\n" +
                "LEFT JOIN cbs_warehouse_sla s ON w.id = s.cbs_warehouse_id\n" +
                "WHERE\n" +
                "\ts.shi = '" + cityCode + "'\n" +
                "AND w.is_close = '0'");
        j.setObj(cbsWarehouseList);
        return j;
    }

    /*
     * 根据发货物流和收货地址所在城市选择仓库
     * */
    @RequestMapping(params = "getWarehouseByLogistics")
    @ResponseBody
    public AjaxJson getWarehouseByLogistics(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String logistics = request.getParameter("logistics");
        List<Map<String, Object>> cbsWarehouseList = null;
        if (logistics.equals("0")) {
            cbsWarehouseList = systemService.findForJdbc("SELECT\n" +
                    "\tw.id AS id,\n" +
                    "\tw.`name` AS `name`,w.user_name AS userName,w.phone AS phone,w.email AS email,\n" +
                    "\tw.logistics AS logistics\n" +
                    "FROM\n" +
                    "\tcbs_warehouse w\n" +
                    "WHERE\n" +
                    "w.is_close = '0'");
        } else {
            cbsWarehouseList = systemService.findForJdbc("SELECT\n" +
                    "\tw.id AS id,\n" +
                    "\tw.`name` AS `name`,w.user_name AS userName,w.phone AS phone,w.email AS email,\n" +
                    "\tw.logistics AS logistics\n" +
                    "FROM\n" +
                    "\tcbs_warehouse w\n" +
                    "WHERE\n" +
                    "w.is_close = '0' and w.logistics = '" + logistics + "'");
        }

        if (cbsWarehouseList != null && cbsWarehouseList.size() > 0) {
            j.setObj(cbsWarehouseList);
        }
        return j;
    }

    /*
     * 根据发货物流和收货地址所在城市选择仓库
     * */
    @RequestMapping(params = "getWarehouseByLogisticsForCity")
    @ResponseBody
    public AjaxJson getWarehouseByLogisticsForCity(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String cityCode = request.getParameter("cityCode");
        String logistics = request.getParameter("logistics");
        List<Map<String, Object>> cbsWarehouseList = systemService.findForJdbc("SELECT\n" +
                "\tw.id AS id,\n" +
                "\tw.`name` AS `name`,\n" +
                "\tw.user_name AS userName,\n" +
                "\tw.phone AS phone,\n" +
                "\tw.email AS email,\n" +
                "\tw.logistics AS logistics,\n" +
                "\ts.is_priority AS isPriority\n" +
                "FROM\n" +
                "\tcbs_warehouse w\n" +
                "LEFT JOIN cbs_warehouse_sla s on w.id=s.cbs_warehouse_id\n" +
                "WHERE\n" +
                "\tw.is_close = '0'\n" +
                "and s.shi = '" + cityCode + "'\n" +
                "AND w.logistics = '" + logistics + "' and s.is_priority='1' ");
        if (cbsWarehouseList != null && cbsWarehouseList.size() > 0) {
            j.setObj(cbsWarehouseList);
        }
        return j;
    }

    /*
     * 根据仓库选择sla
     * */
    @RequestMapping(params = "getSLAByWarehouse")
    @ResponseBody
    public AjaxJson getSLAByWarehouse(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String code = request.getParameter("deliverWarehouseId");
        String city = request.getParameter("city");

        String hql = "from CbsWarehouseSlaEntity where cbsWarehouseId='" + code + "' and shi='" + city + "'";
        CbsWarehouseSlaEntity sla = systemService.singleResult(hql);
        System.out.println("sla:" + sla);

        j.setObj(sla);
        return j;
    }

    /*
     * 根据仓库获取联系人
     * */
    @RequestMapping(params = "getWarehouseContacts")
    @ResponseBody
    public AjaxJson getWarehouseContacts(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String id = request.getParameter("code");
        CbsWarehouseEntity warehouse = systemService.get(CbsWarehouseEntity.class, id);

        j.setObj(warehouse);
        return j;
    }

    /*
     * 根据物流获取联系人f
     * */
    @RequestMapping(params = "getContacts")
    @ResponseBody
    public AjaxJson getContacts(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String code = request.getParameter("code");
        System.out.println("codeaaaaa:" + code);

        String hql = "from TSDepart where departname='" + code + "' and orgType='logistics'";
        TSDepart tsDepartList = systemService.singleResult(hql);
        System.out.println("tsDepartList:" + tsDepartList);
        List<ZyContactsEntity> zyContacts = null;
        if (StringUtil.isNotEmpty(tsDepartList)) {
            String id = tsDepartList.getId();
            System.out.println("id:" + id);
            String sql = "from ZyContactsEntity where belongOrg.id='" + id + "'";
            zyContacts = systemService.findHql(sql);
            System.out.println("zyContacts:" + zyContacts);
            if (zyContacts.size() > 0 && zyContacts != null) {
                j.setObj(zyContacts.get(0));
            }
        } else {
            j.setObj(zyContacts);
        }

        return j;
    }

    /*
     * 根据省获取影院
     * */
    @RequestMapping(params = "getCinema")
    @ResponseBody
    public AjaxJson getCinema(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String city = request.getParameter("city");
        System.out.println("city:" + city);

        String hql = "from ZyCinemaEntity where province.id='" + city + "'";
        List<ZyCinemaEntity> cinemaList = systemService.findHql(hql);
        if (cinemaList.size() > 0) {
            System.out.println("cinema:" + cinemaList.get(0).getName());
        }
        j.setObj(cinemaList);
        return j;
    }

    /*
     * 根据id获取影院
     * */
    @RequestMapping(params = "getCinemaAddress")
    @ResponseBody
    public AjaxJson getCinemaAddress(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String cinemaid = request.getParameter("cinemaid");
        System.out.println("cinemaid:" + cinemaid);

        ZyCinemaEntity cinema = systemService.get(ZyCinemaEntity.class, cinemaid);

        j.setObj(cinema);

        return j;
    }

    /*
     * 根据申请优先级
     * */
    @RequestMapping(params = "getApplyLayer")
    @ResponseBody
    public AjaxJson getApplyLayer(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String hql = "from TSType where TSTypegroup.typegroupcode='apply_layer'";
        List<TSType> applyLayerList = systemService.findHql(hql);
        j.setObj(applyLayerList);
        return j;
    }

    @RequestMapping(params = "sendChooseCm")
    public ModelAndView sendChooseCm(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbs_deliver/sendChooseCm");
    }
/************************************************************************************************************************/
    /**
     * 添加发货单信息
     * 马宏刚\yangwp\zby
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(CbsDelinerEntity cbsDeliner, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        //获取登录的用户信息
        TSUser user = ResourceUtil.getSessionUserName();
        try {
            String fhSheng = request.getParameter("fhSheng");  //收货人省
            String shiId = request.getParameter("fhShi"); //收货人市
            String ztWarehouseId = request.getParameter("ztWarehouseId");  //自提地址id
            String deliverWarehouseId = request.getParameter("delinerWarehouseId"); //发货所在仓库
            String wlSLA = request.getParameter("wlSla");  //物流承诺sla
            String cinemaId = request.getParameter("cinemaName");  //影院名称

            //发货仓库
            CbsWarehouseEntity deliverWarehouse = null;
            if (deliverWarehouseId != null && deliverWarehouseId != "") {
                deliverWarehouse = systemService.singleResult("from CbsWarehouseEntity where id='" + deliverWarehouseId + "'");
            }
            //设置收货人地址
            TSTerritory sheng = null;
            TSTerritory shi = new TSTerritory();
            if (StringUtil.isNotEmpty(fhSheng)) {
                sheng = systemService.singleResult("from TSTerritory  where territoryCode = '" + fhSheng + "'");
            }
            if (StringUtil.isNotEmpty(shiId)) {
                shi.setId(shiId);
            }

            //根据是否自提存储发货单的省市
            if (request.getParameter("zt") != null) {
                cbsDeliner.setZt(Integer.valueOf(request.getParameter("zt")));
                if (Integer.valueOf(request.getParameter("zt")) == 1) {  //是
                    //自提仓库,如果是自提，将自提的仓库id保存后，将自提仓库的省市也保存
                    CbsWarehouseEntity ztCbsWarehouse = null;
                    if (ztWarehouseId != null && ztWarehouseId != "") {
                        ztCbsWarehouse = systemService.singleResult("from CbsWarehouseEntity where id='" + ztWarehouseId + "'");
                        cbsDeliner.setWarehouseId(ztCbsWarehouse);
                        cbsDeliner.setAddress(ztCbsWarehouse.getAddress());
                        cbsDeliner.setSheng(ztCbsWarehouse.getSheng());
                        cbsDeliner.setShi(ztCbsWarehouse.getShi());
                    }
                }
                if (Integer.valueOf(request.getParameter("zt")) == 2) {  //否
                    cbsDeliner.setAddress(request.getParameter("address").replace("\"", ""));
                    cbsDeliner.setSheng(sheng);
                    cbsDeliner.setShi(shi);
                    cbsDeliner.setCinemaName(cinemaId.replace("\"", ""));
                }
            }

            //设置物流提货地址
            String thProvince = request.getParameter("thProvince"); //物流提货省
            String thShi = request.getParameter("thShi"); //物流提货市
            TSTerritory thProvinces = null;
            TSTerritory thCity = new TSTerritory();
            if (StringUtil.isNotEmpty(thProvince)) {
                thProvinces = systemService.singleResult("from TSTerritory  where territoryCode = '" + thProvince + "'");
                cbsDeliner.setThSheng(thProvinces);
            }
            if (StringUtil.isNotEmpty(thShi)) {
                thCity.setId(thShi);
                cbsDeliner.setThCity(thCity);
            }
            cbsDeliner.setThAddress(request.getParameter("addressTh"));
            //发货单关联信息保存
            if (StringUtil.isNotEmpty(request.getParameter("srCode"))) {
                cbsDeliner.setSrCode(request.getParameter("srCode"));
            }
            if (StringUtil.isNotEmpty(request.getParameter("crCode"))) {
                cbsDeliner.setCrCode(request.getParameter("crCode"));
            }
            if (StringUtil.isNotEmpty(request.getParameter("soCode"))) {
                cbsDeliner.setSoCode(request.getParameter("soCode"));
            }
            cbsDeliner.setDeliverType(request.getParameter("deliverType"));

            /*收货人姓名和电话*/
            cbsDeliner.setUserName(request.getParameter("userName"));
            cbsDeliner.setPhone(request.getParameter("phone"));

            /*物流信息*/
            cbsDeliner.setWlSLA(wlSLA);
            cbsDeliner.setDeliverWarehouseId(deliverWarehouse);
            cbsDeliner.setDeliverDes(request.getParameter("deliverDes"));
            cbsDeliner.setDeliverLogistics(request.getParameter("deliverLogisticsId"));
            cbsDeliner.setReturnLogistics(request.getParameter("retrunLogistics"));
            cbsDeliner.setFhSLA(request.getParameter("sendSLA"));
            cbsDeliner.setwLocaltion(request.getParameter("warehouseLocaltion"));
            cbsDeliner.setStatus(StaticValue.CSAdfh);  //新建时默认为CSA待发货状态
            cbsDeliner.setCreateName(user.getRealName());  
            cbsDeliner.setCreateBy(user.getUserName());  

            //组装发货单号FH+YYYYMMDD+001(增长) 组成发货单号
            String deliverCode = cbsDelinerService.getDelinerCode();
            cbsDeliner.setCode(deliverCode);

            /*更新后保存发货单*/
            message = "发货单信息添加成功";
            cbsDelinerService.save(cbsDeliner);

            //根据发货单填写的cr号，更新服务单的sr号，so号
            if (StringUtil.isNotEmpty(request.getParameter("crCode"))) {
                CbsServiceEntity service = systemService.singleResult("from CbsServiceEntity where code='" + request.getParameter("crCode") + "'");
                if (service != null) {
                    if (StringUtil.isNotEmpty(request.getParameter("soCode")) && !request.getParameter("soCode").equals(service.getSo())) {
                        //增加服务单日志，发货单修改了so
                        cbsServiceLogServiceI.addServiceLog(service, StaticValue.Close_Service_Log_Type_2, "发货单:" + cbsDeliner.getCode() + "修改服务单so：" + service.getSo() + "为：" + request.getParameter("soCode"), null);
                        service.setSo(request.getParameter("soCode"));
                    }
                    if (StringUtil.isNotEmpty(request.getParameter("srCode")) && !request.getParameter("srCode").equals(service.getSr())) {
                        //增加服务单日志，发货单修改了sr
                        cbsServiceLogServiceI.addServiceLog(service, StaticValue.Close_Service_Log_Type_2, "发货单:" + cbsDeliner.getCode() + "修改了服务单sr：" + service.getSr() + "为：" + request.getParameter("srCode"), null);
                        service.setSr(request.getParameter("srCode"));
                    }
                    systemService.saveOrUpdate(service);
                }
            }

            //获取库位
            List<TSType> types = systemService.findHql("from TSType where TSTypegroup.typegroupcode='kuwei'");
            request.setAttribute("types", types);

            //设置备件信息
            String eq = request.getParameter("equipment");
            JSONArray json = JSONArray.fromObject(eq);
            System.out.println("json:" + json);

            ZyEquipmentTypeEntity zyEquipmentType = null;  //备件类型
            ZyEsItemEntity zyEsItem = null;   //备件号
            int count = 0;
            for (int i = 0; i < json.size(); i++) {
                JSONObject jsonOne = json.getJSONObject(i);
                System.out.println("jsonOne:" + jsonOne);
                String total = jsonOne.getString("total");
                String item = jsonOne.getString("item");
                String itemId = jsonOne.getString("itemId");
                String typeId = jsonOne.getString("equipmentType");
                String sn = jsonOne.getString("sn");
                String memo = jsonOne.getString("memo");
                String applyReason = jsonOne.getString("applyReason");
                String applyLayer = jsonOne.getString("applyLayer");
                String isReturn = jsonOne.getString("isReturn");
                if (isReturn.equals("2")) {
                    count++;
                }
                if (typeId != null) {
                    zyEquipmentType = zyEquipmentTypeService.singleResult("from ZyEquipmentTypeEntity where id='" + typeId + "'");
                }
                if (itemId != null) {
                    zyEsItem = systemService.get(ZyEsItemEntity.class, itemId);
                }
                if (total != null && !total.equals("")) {
                    int r = Integer.valueOf(total);
                    for (int k = 0; k < r; k++) {
                        CbsDeliverEquipmentEntity cbsDeliverEquipment = new CbsDeliverEquipmentEntity();
                        //设置备件类型
                        cbsDeliverEquipment.setTypeId(zyEquipmentType);
                        if (zyEquipmentType != null) {
                            cbsDeliverEquipment.setTypeDes(zyEquipmentType.getTypeDesc());
                        }

                        //设置备件号
                        if (item == null || item.equals("")) {
                            cbsDeliverEquipment.setItemId(zyEsItem);
                            if (zyEsItem != null) {
                                cbsDeliverEquipment.setItem(zyEsItem.getItem());
                            }
                        } else {
                            cbsDeliverEquipment.setItem(item.trim());
                        }

                        //设置 equipment_apply_detail_id
                        cbsDeliverEquipment.setEquipmentApplyDetailId(null);

                        //设置其他参数
                        cbsDeliverEquipment.setTotal(1);
                        cbsDeliverEquipment.setSn(sn);
                        cbsDeliverEquipment.setMemo(memo);
                        cbsDeliverEquipment.setIsReturn(Integer.valueOf(isReturn));
                        TSType applyReasonT = systemService.singleResult("from TSType where typecode='" + applyReason + "' and TSTypegroup.typegroupcode='apply_reason'");
                        if (applyReasonT != null) {
                            cbsDeliverEquipment.setApplyReason(applyReasonT.getTypename());
                        }
                        if (!applyLayer.equals("")) {
                            cbsDeliverEquipment.setApplyLayer(Integer.valueOf(applyLayer));
                        }
                        //设置发货单号
                        cbsDeliverEquipment.setDeliverId(cbsDeliner);
                        //保存对象
                        cbsDeliverEquipmentService.save(cbsDeliverEquipment);
                    }
                }
            }

            if (count >= 1) {
                //如果有返件，创建返件任务
                CbsReturnEquipmentEntity returnEquipment = new CbsReturnEquipmentEntity();
                //组装返件单号FH+YYYYMMDD+001(增长)
                Date date1 = new Date();
                DateFormat format1 = new SimpleDateFormat("YYYYMMdd");
                String time1 = format1.format(date1);
                StringBuffer buffer1 = new StringBuffer();
                buffer1.append("FJ");
                buffer1.append(time1);
                List<Object[]> returnEquipmentList = systemService.findListbySql("select * from cbs_return_equipment where to_days(create_date) = to_days(now()) ORDER BY `code` desc;");
                if (returnEquipmentList.size() == 0) {
                    buffer1.append("001");
                    String s = buffer1.toString();
                    returnEquipment.setCode(s);
                } else {
                    String o = (String) returnEquipmentList.get(0)[1];
                    String s = o.substring(10, 13);
                    int l = Integer.parseInt(s);
                    l++;
                    if (l <= 9) {
                        buffer1.append("00" + l);
                    } else if (l >= 10 && l < 100) {
                        buffer1.append("0" + l);
                    } else {
                        buffer1.append("" + l);
                    }
                    String string = buffer1.toString();
                    returnEquipment.setCode(string);
                }
                returnEquipment.setSrCode(StringUtil.isNotEmpty(cbsDeliner.getSrCode()) ? cbsDeliner.getSrCode() : "");
                returnEquipment.setCinemaName(cbsDeliner.getCinemaName());
                returnEquipment.setName(cbsDeliner.getUserName());
                returnEquipment.setPhone(cbsDeliner.getPhone());
                returnEquipment.setAddress(cbsDeliner.getAddress());
                returnEquipment.setSoCode(StringUtil.isNotEmpty(cbsDeliner.getSoCode()) ? cbsDeliner.getSoCode() : "");
                returnEquipment.setDeliverCode(cbsDeliner.getCode());
                returnEquipment.setCrCode(cbsDeliner.getCrCode());
                returnEquipment.setEquipmentApplyId(cbsDeliner.getEquipmentApplyId());
                returnEquipment.setStatus(StaticValue.RETURN_STATUS_Log_Type_1);
                returnEquipment.setLogistics(cbsDeliner.getReturnLogistics());
                returnEquipment.setSheng(cbsDeliner.getSheng());
                returnEquipment.setShi(cbsDeliner.getShi());
                cbsReturnEquipmentServiceI.save(returnEquipment);
                List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + cbsDeliner.getId() + "'");
                for (CbsDeliverEquipmentEntity deliverEquipment : deliverEquipmentList) {
                    if (deliverEquipment.getIsReturn() == 2) {
                        CbsReturnEquipmentDetailEntity returnEquipmentDetail = new CbsReturnEquipmentDetailEntity();
                        returnEquipmentDetail.setReturnEquipmentId(returnEquipment);
                        returnEquipmentDetail.setTypeId(deliverEquipment.getTypeId());
                        if (deliverEquipment.getTypeDes() != null) {
                            returnEquipmentDetail.setTypeDes(deliverEquipment.getTypeDes());
                        }
                        if (deliverEquipment.getItem() != null) {
                            returnEquipmentDetail.setItem(deliverEquipment.getItem());
                        }
                        returnEquipmentDetail.setItemId(deliverEquipment.getItemId());
                        returnEquipmentDetail.setItemTotal(deliverEquipment.getTotal());
                        returnEquipmentDetail.setSn(deliverEquipment.getSn());
                        returnEquipmentDetail.setDeliverEquipmentId(deliverEquipment);
                        cbsReturnEquipmentDetailServiceI.save(returnEquipmentDetail);
                    }

                }

                //创建返件日志
                CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                cbsHandleLogEntity.setBusinessId(returnEquipment.getId());
                cbsHandleLogEntity.setLogType(4);
                cbsHandleLogEntity.setDescription("创建返件申请单");
                cbsHandleLogEntity.setCreateName(user.getRealName());
                cbsHandleLogEntity.setCreateBy(user.getUserName());
                systemService.saveOrUpdate(cbsHandleLogEntity);
            }

            //添加发货单操作日志

            cbsDelinerService.addDeliverLog(user.getRealName() + "创建了发货单", cbsDeliner.getId(), 1);


/*            String emailTitle = "巴可发货通知：<" + cbsDeliner.getCode() + ">-<" + cbsDeliner.getCrCode() + ">-<" + cbsDeliner.getCinemaName() + ">-" + getDateStr(new Date());
            //给仓库联系人发邮件和短信
            cbsDelinerService.sendMail(cbsDeliner, user, "ck", emailTitle, "mail_deliver_CSASend.ftl");
            cbsDelinerService.sendMsg(cbsDeliner, user, "ck", "message_deliver_CSASend.ftl");
            //物流联系人发邮件和短信
            cbsDelinerService.sendMail(cbsDeliner, user, "wl", emailTitle, "mail_deliver_CSASend.ftl");
            cbsDelinerService.sendMsg(cbsDeliner, user, "wl", "message_deliver_CSASend.ftl");*/

            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "发货单信息添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }


    /*
     * 为审核通过的备件申请单自动创建发货单
     * */

    @RequestMapping(params = "autoDoAdd")
    @ResponseBody
    public AjaxJson autoDoAdd(CbsDelinerEntity cbsDeliner, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        //获取页面传回的备件申请单id
        String id = request.getParameter("id");

        //根据id查询备件申请单信息
        CbsEquipmentApplyEntity equipmentApply = systemService.getEntity(CbsEquipmentApplyEntity.class, id);
        Integer zt = equipmentApply.getZt();
        String srCode = equipmentApply.getSrCode();
        String serviceId = equipmentApply.getServiceId();
        String address = equipmentApply.getAddress();
        TSTerritory sheng = equipmentApply.getSheng();
        TSTerritory shi = equipmentApply.getShi();
        String userName = equipmentApply.getUserName();
        String phone = equipmentApply.getPhone();
        String cinemaName = equipmentApply.getCinemaName();
        String warehouseId = equipmentApply.getWarehouseId();
        String memo = equipmentApply.getMemo();
        try {
            CbsServiceEntity service = systemService.get(CbsServiceEntity.class, serviceId);

            //将 申请单id,服务单ID,是否自提,影院名称,所在省,所在市,具体地址,仓库id等信息添加进发货单表
            cbsDeliner.setZt(zt);
            cbsDeliner.setCrCode(service.getCode());
            cbsDeliner.setSoCode(service.getSo());
            cbsDeliner.setSrCode(srCode);
            cbsDeliner.setAddress(address);
            cbsDeliner.setSheng(sheng);
            cbsDeliner.setShi(shi);
            cbsDeliner.setEquipmentApplyId(equipmentApply);
            cbsDeliner.setUserName(userName);
            cbsDeliner.setPhone(phone);
            cbsDeliner.setCinemaName(cinemaName);
            cbsDeliner.setSpaceNumber(equipmentApply.getRecordId());
            cbsDeliner.setCreateDate(new Date());
            if (warehouseId != null && warehouseId != "") {
                CbsWarehouseEntity ztWarehouse = systemService.get(CbsWarehouseEntity.class, warehouseId);
                cbsDeliner.setWarehouseId(ztWarehouse);
            }

            //根据城市获取推荐物流
            if (shi != null) {
                List<Map<String, Object>> wList = systemService.findForJdbc("SELECT\n" +
                        "\tw.id AS id,\n" +
                        "\tw.`name` AS `name`,w.phone AS phone,w.email AS email,w.user_name AS userName,\n" +
                        "\tw.logistics AS logistics,\n" +
                        "\ts.is_priority AS isPriority,\n" +
                        "\tCASE\n" +
                        "WHEN s.sla_type = '1' THEN\n" +
                        "\t'SL1'\n" +
                        "WHEN s.sla_type = '2' THEN\n" +
                        "\t'SL2'\n" +
                        "WHEN s.sla_type = '3' THEN\n" +
                        "\t'SL3'\n" +
                        "WHEN s.sla_type = '4' THEN\n" +
                        "\t'SL4'\n" +
                        "ELSE\n" +
                        "\t'无'\n" +
                        "END AS slaType\n" +
                        "FROM\n" +
                        "\tcbs_warehouse w\n" +
                        "LEFT JOIN cbs_warehouse_sla s ON w.id = s.cbs_warehouse_id\n" +
                        "WHERE\n" +
                        "\ts.shi = '" + shi.getId() + "'\n" +
                        "AND s.is_priority = '1'\n" +
                        "ORDER BY s.sla_type DESC");
                if (wList != null && wList.size() > 0 && wList.get(0) != null) {
                    cbsDeliner.setDeliverLogistics((String) wList.get(0).get("logistics"));
                    cbsDeliner.setWlSLA((String) wList.get(0).get("slaType"));
                    CbsWarehouseEntity wareHouse = systemService.get(CbsWarehouseEntity.class, (String) wList.get(0).get("id"));
                    if (wareHouse != null) {
                        cbsDeliner.setDeliverWarehouseId(wareHouse);
                    }
                }
            }
            cbsDeliner.setDeliverType("1");
            cbsDeliner.setStatus(StaticValue.CSAdfh);
            cbsDeliner.setFhSLA("1");
            String deliverCode = cbsDelinerService.getDelinerCode();
            cbsDeliner.setCode(deliverCode);
            cbsDelinerService.save(cbsDeliner);
            message = "发货单信息添加成功";
            //根据备件申请单id查询申请备件信息
            List<CbsEquipmentApplyDetailEntity> equipmentApplyDetailList = systemService.findHql("from CbsEquipmentApplyDetailEntity where applyId.id='" + id + "'");
            if (equipmentApplyDetailList.size() > 0 && equipmentApplyDetailList != null) {
                for (CbsEquipmentApplyDetailEntity ead : equipmentApplyDetailList) {
                    int totle = ead.getTotal();
                    if (totle > 0) {
                        for (int i = 0; i < totle; i++) {
                            CbsDeliverEquipmentEntity cbsDeliverEquipment = new CbsDeliverEquipmentEntity();
                            //设置备件信息
                            cbsDeliverEquipment.setDeliverId(cbsDeliner);
                            cbsDeliverEquipment.setEquipmentApplyDetailId(ead);
                            cbsDeliverEquipment.setApplyLayer(ead.getApplyLayer());
                            if (ead != null) {
                                cbsDeliverEquipment.setTypeDes(ead.getTypeDes());
                                cbsDeliverEquipment.setTypeId(ead.getTypeId());
                            }
                            if (ead != null) {
                                if (ead.getItemId() != null) {
                                    cbsDeliverEquipment.setItemId(ead.getItemId());
                                    //根据备件号查询是否需要返件
                                    if (ead.getItemId().getIsReturn() != null) {
                                        if (ead.getItemId().getIsReturn().equals("1")) {//需要返件
                                            cbsDeliverEquipment.setIsReturn(2);
                                        }
                                        if (ead.getItemId().getIsReturn().equals("2")) {//不需要返件
                                            cbsDeliverEquipment.setIsReturn(1);
                                        }

                                    }
                                } else {
                                    cbsDeliverEquipment.setIsReturn(1);
                                }
                                cbsDeliverEquipment.setItem(ead.getItem());
                            }
                            cbsDeliverEquipment.setTotal(1);
                            cbsDeliverEquipment.setMemo(memo);
                            cbsDeliverEquipment.setApplyReason(equipmentApply.getApplyReason());
                            //保存备件
                            cbsDeliverEquipmentService.save(cbsDeliverEquipment);
                        }
                    }


                }
            } else {
                CbsDeliverEquipmentEntity cbsDeliverEquipment = new CbsDeliverEquipmentEntity();
                cbsDeliverEquipment.setDeliverId(cbsDeliner);
                cbsDeliverEquipmentService.save(cbsDeliverEquipment);
            }
            //记录操作日志
            //获取登录的用户信息
            TSUser user = ResourceUtil.getSessionUserName();
            cbsDelinerService.addDeliverLog(user.getRealName() + "创建了发货单", cbsDeliner.getId(), 1);
            //系统自动发送通知给CSA
//            CbsServiceEntity cbsService = systemService.getEntity(CbsServiceEntity.class, equipmentApply.getServiceId());
//            ZyEngineerEntity enginner = null;
//            TSDepart fws = null;
//            if (service != null) {
//                if (service.getEngineer() != null &&!service.getEngineer().equals("")) {
//                    enginner = systemService.get(ZyEngineerEntity.class, service.getEngineer());
//                }
//                if (service.getServiceProviderCode() != null && !service.getServiceProviderCode().equals("")) {
//                    fws = systemService.singleResult("from TSDepart where orgCode='" + service.getServiceProviderCode() + "'");
//                }
//            }
//            TSUser approveUser = systemService.get(TSUser.class, equipmentApply.getApproveUser());
//            if (enginner != null && fws != null &&approveUser!=null) {
//                List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSRole.roleCode='"+StaticValue.RULE_CODE_BARCO_CSA_ZB+"'");
//                String emailTital = "备件发货申请:<" + cbsDeliner.getCode() + ">-<" + cbsService.getLevel() + ">-<" + service.getCode() + ">-<" + cbsDeliner.getCinemaName() + ">" + getDateStr(new Date());
//                String emailContent = "Dear CSA同事们，请安排以下发货。\n" + "发货单号：" + cbsDeliner.getCode() + "。\n" +
//                        "备件申请人：" + fws.getDepartname() + "  " + enginner.getName() + " " + enginner.getCellphone() + "。\n" +
//                        "备件审批人：" + approveUser.getRealName() + "  " + approveUser.getMobilePhone() + "。\n" +
//                        "具体内容请查看http://cbs.cfg-barco.com\n" + "【中影巴可客服部】\n" + "* 该邮件请勿回复";
//                if(tsRoleUserList!=null && tsRoleUserList.size()>0){
//                    for (TSRoleUser ru : tsRoleUserList) {
//                        if(StringUtil.isNotEmpty(ru.getTSUser())&&ru.getTSUser().getStatus().equals(Globals.User_Normal)){  //用户状态为正常情况
//                            if(ru!=null && ru.getTSUser()!=null && ru.getTSUser().getEmail()!=null && !ru.getTSUser().getEmail().equals("")){
//                                String email = ru.getTSUser().getEmail();
//                                SendMailUtil.sendeMail(email, emailTital, emailContent, systemService);
//                            }
//
//                        }
//
//                    }
//                }
//
//            }

        } catch (Exception e) {
            e.printStackTrace();
            message = "发货单信息添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);

        return j;
    }


    /**************************************************************************************************/
    /**
     * 发货单信息详情页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goDeliverDetails")
    public ModelAndView goDeliverDetails(CbsDelinerEntity cbsDeliner, HttpServletRequest req) {

        if (StringUtil.isNotEmpty(cbsDeliner.getId())) {
            System.out.println("id:" + cbsDeliner.getId());
            cbsDeliner = cbsDelinerService.getEntity(CbsDelinerEntity.class, cbsDeliner.getId());
            if (cbsDeliner.getDeliverWarehouseId() != null) {
//				String slaType = cbsDeliner.getDeliverWarehouseId().getSlaId().getSlaType();
//				req.setAttribute("slaType",slaType);
            }
            req.setAttribute("cbsDelinerPage", cbsDeliner);

        }
        List<CbsServiceEntity> cbsServiceEntityList = systemService.findHql("FROM CbsServiceEntity where code = '" + cbsDeliner.getCrCode() + "'");
        if (cbsServiceEntityList!=null && cbsServiceEntityList.size() > 0) {
        	req.setAttribute("servicetype", cbsServiceEntityList.get(0).getServiceType2().getName());
        }
        
        String type = req.getParameter("type");
        req.setAttribute("type", type);
        if (cbsDeliner.getSignFile() != null) {
            ZyFileLogEntity zyFileLogEntity = systemService.getEntity(ZyFileLogEntity.class, cbsDeliner.getSignFile());
            req.setAttribute("zyFileLogEntity", zyFileLogEntity);
        }
        //获取所有的发货单类型
        String hql = "from TSType where TSTypegroup.typegroupcode='Deliver_Type'";
        List<TSType> deliverTypeList = systemService.findHql(hql);
        req.setAttribute("deliverTypeList", deliverTypeList);

        //获取发货单状态
        TSType deliverStatus = systemService.singleResult("from TSType where typecode='" + cbsDeliner.getStatus() + "' and TSTypegroup.typegroupcode='deliver_status'");
        req.setAttribute("deliverStatus", deliverStatus);
        List<ZyFileLogEntity> zyFileLogEntityListSign = systemService.findHql("from ZyFileLogEntity where businessKey = '" + cbsDeliner.getId() + "' and businessType = 'S'");
        if (zyFileLogEntityListSign != null && zyFileLogEntityListSign.size() > 0) {
            req.setAttribute("zyFileLogEntityListSign", zyFileLogEntityListSign);
        } else {
            req.setAttribute("zyFileLogEntityListSign", null);
        }
        List<ZyFileLogEntity> zyFileLogEntityList = systemService.findHql("from ZyFileLogEntity where businessKey = '" + cbsDeliner.getId() + "' and businessType = 'L'");
        if (zyFileLogEntityList != null && zyFileLogEntityList.size() > 0) {
            req.setAttribute("zyFileLogEntityListSend", zyFileLogEntityList);
        } else {
            req.setAttribute("zyFileLogEntityListSend", null);
        }
        //获取欠货时长
        Date d = new Date();
        Date QHTime = cbsDeliner.getQHTime();
        //根据发货单状态计算欠货时长
        String qhtime = "";
        //判断是否标记过欠货
        if (QHTime == null) {
            //没有标记过欠货
            qhtime = "";
        } else {
            if (deliverStatus.getTypename().equals("欠货中")) {
                qhtime = (d.getTime() - QHTime.getTime()) / 1000 / 60 / 60 / 24 + "";
            } else if (deliverStatus.getTypename().equals("已取消")) {
                qhtime = "";
            } else {
                if (cbsDeliner.getCSASendTime() != null) {
                    qhtime = (cbsDeliner.getCSASendTime().getTime() - QHTime.getTime()) / 1000 / 60 / 60 / 24 + "";
                } else {
                    qhtime = (d.getTime() - QHTime.getTime()) / 1000 / 60 / 60 / 24 + "";
                }
            }
        }

        req.setAttribute("qhtime", qhtime);


        //根据发货单号获取申请的备件
        List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + cbsDeliner.getId() + "'");
        req.setAttribute("deliverEquipmentList", deliverEquipmentList);

        //查询所有备件号
        List<ZyEsItemEntity> equipmentCodeList = zyEsItemService.findHql("from ZyEsItemEntity");
        req.setAttribute("equipmentCodeList", equipmentCodeList);

        //查询所有备件型号
        List<ZyEquipmentTypeEntity> equipmentTypeList = new ArrayList<ZyEquipmentTypeEntity>();
        List<ZyEquipmentTypeEntity> list = systemService.findHql("from ZyEquipmentTypeEntity");
        for (ZyEquipmentTypeEntity et : list) {
            List<ZyEquipmentTypeEntity> list2 = zyEquipmentTypeService.findHql("from ZyEquipmentTypeEntity where equipmentType.id='" + et.getId() + "'");
            if (list2.size() <= 0) {
                equipmentTypeList.add(et);
            }
        }
        req.setAttribute("equipmentTypeList", equipmentTypeList);

        //获取申请优先级
        List<TSType> applyLayerList = systemService.findHql("from TSType where TSTypegroup.typegroupcode='apply_layer'");
        req.setAttribute("applyLayerList", applyLayerList);

        //获取所有的省
        List<TSTerritory> shengList = systemService.findHql("from TSTerritory where territoryLevel='1'");
        req.setAttribute("shengList", shengList);

        //根据发货物流获取对应的联系人
        TSDepart tsDepart = null;
        List<ZyContactsEntity> zyContacts = null;
        if (cbsDeliner.getDeliverLogistics() != null && cbsDeliner.getDeliverLogistics() != "") {
            tsDepart = systemService.singleResult("from TSDepart where departname='" + cbsDeliner.getDeliverLogistics() + "' and orgType='logistics'");
            if (StringUtil.isNotEmpty(tsDepart)) {
                zyContacts = systemService.findHql("from ZyContactsEntity where belongOrg.id='" + tsDepart.getId() + "'");
            }
            if (zyContacts != null && zyContacts.size() > 0) {
                req.setAttribute("zyContacts", zyContacts.get(0));
            } else {
                req.setAttribute("zyContacts", null);
            }
        }


        //根据返件物流获取对应的联系人
        List<ZyContactsEntity> returnContacts = null;
        TSDepart tsDepart2 = systemService.singleResult("from TSDepart where departname='" + cbsDeliner.getReturnLogistics() + "' and orgType='logistics'");
        if (tsDepart2 != null) {
            returnContacts = systemService.findHql("from ZyContactsEntity where belongOrg.id='" + tsDepart2.getId() + "'");
//            req.setAttribute("returnContacts", returnContacts);
            if (zyContacts != null && zyContacts.size() > 0) {
                req.setAttribute("returnContacts", returnContacts.get(0));
            } else {
                req.setAttribute("returnContacts", null);
            }
        }

        //获取发货sla
        TSType fhSLA = null;
        if (cbsDeliner.getFhSLA() != null && cbsDeliner.getFhSLA() != "") {
            fhSLA = systemService.singleResult("from TSType where typecode='" + cbsDeliner.getFhSLA() + "' and TSTypegroup.typegroupcode='fhSLA'");
        }
        req.setAttribute("fhSLA", fhSLA);


        //获取库位
        TSType kuwei = null;
        if (cbsDeliner.getwLocaltion() != null && cbsDeliner.getwLocaltion() != "") {
            kuwei = systemService.singleResult("from TSType where typecode='" + cbsDeliner.getwLocaltion() + "' and TSTypegroup.typegroupcode='kuwei'");
        }
        req.setAttribute("kuwei", kuwei);


        //查询发货单操作日志
        List<CbsHandleLogEntity> logList = systemService.findHql("from CbsHandleLogEntity where logType=2 and businessId='" + cbsDeliner.getId() + "'  ORDER BY createDate DESC");
        req.setAttribute("logList", logList);

        //查询分派到物流以后的发货单操作日志
        List<CbsHandleLogEntity> logisticsLogList = systemService.findHql("from CbsHandleLogEntity where logType=2 and businessId='" + cbsDeliner.getId() + "' and processStatus=2  ORDER BY createDate DESC");
        req.setAttribute("logisticsLogList", logisticsLogList);

        //获取登录的用户信息
        TSUser user = ResourceUtil.getSessionUserName();
        //用户的角色集合
        List<String> roleList = new ArrayList<>();
        List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSUser.id='" + user.getId() + "'");
        for (TSRoleUser tsRoleUser : tsRoleUserList) {
            String role = tsRoleUser.getTSRole().getRoleCode();
            roleList.add(role);
        }
        //判断登录用户身份
        if (roleList.contains("logistics")) {
            return new ModelAndView("com/zybk/cbs_deliver/cbsDeliner-details-logistics");
        }
        if (roleList.contains("barcoCSA") || roleList.contains("admin")) {
            return new ModelAndView("com/zybk/cbs_deliver/cbsDeliner-details");
        }
        if (roleList.contains("barcoHelpdesk")) {
            return new ModelAndView("com/zybk/cbs_deliver/cbsDeliner-details");
        } else {
            return null;
        }


    }

    /**************************************************************************************************/

    //根据省id获取市
    @RequestMapping(params = "getCityBySheng")
    @ResponseBody
    public AjaxJson getCityBySheng(HttpServletRequest req) {
        AjaxJson json = new AjaxJson();
        String shengId = req.getParameter("province");
        List<TSTerritory> shiList = systemService.findHql("from TSTerritory where territoryLevel='2'and TSTerritory.id='" + shengId + "'");
        json.setObj(shiList);
        return json;
    }

    /**
     * 发货单信息编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(CbsDelinerEntity cbsDeliner, HttpServletRequest req) {

        System.out.println("修改发货单");
        if (StringUtil.isNotEmpty(cbsDeliner.getId())) {
            System.out.println("id:" + cbsDeliner.getId());
            cbsDeliner = cbsDelinerService.getEntity(CbsDelinerEntity.class, cbsDeliner.getId());
            req.setAttribute("cbsDelinerPage", cbsDeliner);

        }
        List<CbsServiceEntity> cbsServiceEntityList = systemService.findHql("FROM CbsServiceEntity where code = '" + cbsDeliner.getCrCode() + "'");
        if (cbsServiceEntityList!=null && cbsServiceEntityList.size() > 0) {
        	req.setAttribute("servicetype", cbsServiceEntityList.get(0).getServiceType2().getName());
        }
        if (cbsDeliner.getSignFile() != null) {
            ZyFileLogEntity zyFileLogEntity = systemService.getEntity(ZyFileLogEntity.class, cbsDeliner.getSignFile());
            req.setAttribute("zyFileLogEntity", zyFileLogEntity);
        }
        //获取所有的发货单类型
        String hql = "from TSType where TSTypegroup.typegroupcode='Deliver_Type'";
        List<TSType> deliverTypeList = systemService.findHql(hql);
        req.setAttribute("deliverTypeList", deliverTypeList);

        //获取发货单状态
        TSType deliverStatus = systemService.singleResult("from TSType where typecode='" + cbsDeliner.getStatus() + "' and TSTypegroup.typegroupcode='deliver_status'");
        req.setAttribute("deliverStatus", deliverStatus);

        //获取欠货时长
        Date d = new Date();
        Date QHTime = cbsDeliner.getQHTime();
        //根据发货单状态计算欠货时长
        String qhtime = "";
        //判断是否标记过欠货
        if (QHTime == null) {
            //没有标记过欠货
            qhtime = "";
        } else {
            if (deliverStatus.getTypename().equals("欠货中")) {
                qhtime = (d.getTime() - QHTime.getTime()) / 1000 / 60 / 60 / 24 + "";
            } else if (deliverStatus.getTypename().equals("已取消")) {
                qhtime = "";
            } else {
                if (cbsDeliner.getCSASendTime() != null) {
                    qhtime = (cbsDeliner.getCSASendTime().getTime() - QHTime.getTime()) / 1000 / 60 / 60 / 24 + "";
                } else {
                    qhtime = (d.getTime() - QHTime.getTime()) / 1000 / 60 / 60 / 24 + "";
                }
            }
        }

        req.setAttribute("qhtime", qhtime);


        //根据发货单号获取申请的备件
        List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + cbsDeliner.getId() + "'");
        req.setAttribute("deliverEquipmentList", deliverEquipmentList);
        //根据备件类型查询备件号
        Map<String, Object> map = new HashMap<>();
        for (CbsDeliverEquipmentEntity eq : deliverEquipmentList) {

            if (eq.getTypeId() != null) {
                List<ZyEsItemEntity> equipmentItemList = equipmentItemList = zyEsItemService.findHql("from ZyEsItemEntity where type.id='" + eq.getTypeId().getId() + "'");
                map.put(eq.getId(), equipmentItemList);
            }
        }

        req.setAttribute("equipmentItemMap", map);
        List<ZyFileLogEntity> zyFileLogEntityListSign = systemService.findHql("from ZyFileLogEntity where businessKey = '" + cbsDeliner.getId() + "' and businessType = 'S'");
        if (zyFileLogEntityListSign != null && zyFileLogEntityListSign.size() > 0) {
            req.setAttribute("zyFileLogEntityListSign", zyFileLogEntityListSign);
        } else {
            req.setAttribute("zyFileLogEntityListSign", null);
        }
        List<ZyFileLogEntity> zyFileLogEntityList = systemService.findHql("from ZyFileLogEntity where businessKey = '" + cbsDeliner.getId() + "' and businessType = 'L'");
        if (zyFileLogEntityList != null && zyFileLogEntityList.size() > 0) {
            req.setAttribute("zyFileLogEntityListSend", zyFileLogEntityList);
        } else {
            req.setAttribute("zyFileLogEntityListSend", null);
        }
        //查询所有备件型号
        List<ZyEquipmentTypeEntity> equipmentTypeList = new ArrayList<ZyEquipmentTypeEntity>();
        List<ZyEquipmentTypeEntity> list = systemService.findHql("from ZyEquipmentTypeEntity");
        for (ZyEquipmentTypeEntity et : list) {
            List<ZyEquipmentTypeEntity> list2 = zyEquipmentTypeService.findHql("from ZyEquipmentTypeEntity where equipmentType.id='" + et.getId() + "'");
            if (list2.size() <= 0) {
                equipmentTypeList.add(et);
            }
        }
        req.setAttribute("equipmentTypeList", equipmentTypeList);

        //根据收货地址和物流获取仓库
        if (cbsDeliner.getShi() != null) {
            if (cbsDeliner.getDeliverLogistics() != null && !cbsDeliner.getDeliverLogistics().equals("")) {
                String sql = "SELECT\n" +
                        "\tcw.name as name,\n" +
                        "\tcw.id as id,cw.user_name AS userName,cw.phone AS phone,cw.email AS email\n" +
                        "FROM\n" +
                        "\tcbs_warehouse cw\n" +
                        "WHERE\n" +
                        "\tcw.is_close = '0'\n" +
                        "and cw.logistics = '" + cbsDeliner.getDeliverLogistics() + "'\n";
                List<Map<String, Object>> wareList = systemService.findForJdbc(sql);
                req.setAttribute("wareList", wareList);
            } else {
                List<Map<String, Object>> wareList = systemService.findForJdbc("select cw.name as name,cw.id as id from cbs_warehouse cw");
                req.setAttribute("wareList", wareList);
            }
        } else {
            if (cbsDeliner.getDeliverLogistics() != null && !cbsDeliner.getDeliverLogistics().equals("")) {
                String sql = "SELECT\n" +
                        "\tcw.name as name,\n" +
                        "\tcw.id as id,cw.user_name AS userName,cw.phone AS phone,cw.email AS email\n" +
                        "FROM\n" +
                        "\tcbs_warehouse cw\n" +
                        "WHERE\n" +
                        "\tcw.is_close = '0'\n" +
                        "AND cw.logistics = '" + cbsDeliner.getDeliverLogistics() + "'";
                List<Map<String, Object>> wareList = systemService.findForJdbc(sql);
                req.setAttribute("wareList", wareList);
            } else {
                List<Map<String, Object>> wareList = systemService.findForJdbc("select cw.name as name,cw.id as id from cbs_warehouse cw");
                req.setAttribute("wareList", wareList);
            }
        }

        //获取申请优先级
        List<TSType> applyLayerList = systemService.findHql("from TSType where TSTypegroup.typegroupcode='apply_layer'");
        req.setAttribute("applyLayerList", applyLayerList);

        //查询所有申请理由
        List<TSType> applyReasonList = systemService.findHql("from TSType where TSTypegroup.typegroupcode='apply_reason'");
        req.setAttribute("applyReasonList", applyReasonList);

        //获取所有的省
        List<TSTerritory> shengList = systemService.findHql("from TSTerritory where territoryLevel='1'");
        req.setAttribute("shengList", shengList);

        //根据省获取市
        List<TSTerritory> shiList = null;
        if (cbsDeliner.getThSheng() != null) {
            shiList = systemService.findHql("from TSTerritory where territoryLevel='2'and TSTerritory.id='" + cbsDeliner.getThSheng().getId() + "'");
        }
        req.setAttribute("shiList", shiList);

        //获取所有发货sla
        List<TSType> fhSLAList = systemService.findHql("from TSType where TSTypegroup.typegroupcode='fhSLA'");
        req.setAttribute("fhSLAList", fhSLAList);

        //根据发货物流获取对应的联系人
        TSDepart tsDepart = null;
        List<ZyContactsEntity> zyContacts = null;
        if (cbsDeliner.getDeliverLogistics() != null && cbsDeliner.getDeliverLogistics() != "") {
            tsDepart = systemService.singleResult("from TSDepart where departname='" + cbsDeliner.getDeliverLogistics() + "' and orgType='logistics'");
            if (StringUtil.isNotEmpty(tsDepart)) {
                zyContacts = systemService.findHql("from ZyContactsEntity where belongOrg.id='" + tsDepart.getId() + "'");
            }
        }
        if (zyContacts != null && zyContacts.size() > 0) {
            req.setAttribute("zyContacts", zyContacts.get(0));
        } else {
            req.setAttribute("zyContacts", null);
        }


        //根据返件物流获取对应的联系人
        TSDepart tsDepart2 = systemService.singleResult("from TSDepart where departname='" + cbsDeliner.getReturnLogistics() + "' and orgType='logistics'");
        if (tsDepart2 != null) {
            List<ZyContactsEntity> returnContacts = systemService.findHql("from ZyContactsEntity where belongOrg.id='" + tsDepart2.getId() + "'");
            if (returnContacts != null && returnContacts.size() > 0) {
                req.setAttribute("returnContacts", returnContacts.get(0));
            } else {
                req.setAttribute("returnContacts", null);
            }
        }

        //获取发货sla
        TSType fhSLA = null;
        if (cbsDeliner.getFhSLA() != null && cbsDeliner.getFhSLA() != "") {
            fhSLA = systemService.singleResult("from TSType where typecode='" + cbsDeliner.getFhSLA() + "' and TSTypegroup.typegroupcode='fhSLA'");
        }
        req.setAttribute("fhSLA", fhSLA);

        //查询所有物流
        List<TSDepart> logisticsList = systemService.findHql("from TSDepart where orgType='logistics' and logicDelete = '0'");
        req.setAttribute("logisticsList", logisticsList);

        //获取库位
        TSType kuwei = null;
        if (cbsDeliner.getwLocaltion() != null && cbsDeliner.getwLocaltion() != "") {
            kuwei = systemService.singleResult("from TSType where typecode='" + cbsDeliner.getwLocaltion() + "' and TSTypegroup.typegroupcode='kuwei'");
        }
        req.setAttribute("kuwei", kuwei);

        //获取所有库位
        List<TSType> kuweiList = systemService.findHql("from TSType where TSTypegroup.typegroupcode='kuwei'");
        req.setAttribute("kuweiList", kuweiList);

        //查询发货单操作日志
        List<CbsHandleLogEntity> logList = systemService.findHql("from CbsHandleLogEntity where logType=2 and businessId='" + cbsDeliner.getId() + "' ORDER BY createDate DESC");
        req.setAttribute("logList", logList);

        //获取登录的用户信息
        TSUser user = ResourceUtil.getSessionUserName();
        //用户的角色集合
        List<String> roleList = new ArrayList<>();
        List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSUser.id='" + user.getId() + "'");
        for (TSRoleUser tsRoleUser : tsRoleUserList) {
            String role = tsRoleUser.getTSRole().getRoleCode();
            roleList.add(role);
        }
        //判断登录用户身份
        if (roleList.contains("logistics")) {
            return new ModelAndView("com/zybk/cbs_deliver/cbsDeliner-update-logistics");
        }
        if (roleList.contains("barcoCSA") || roleList.contains("admin")) {
            return new ModelAndView("com/zybk/cbs_deliver/cbsDeliner-update");
        } else {
            return null;
        }


    }

    /**
     * 克隆
     */
    @RequestMapping(params = "copyThisInvoice")
    @ResponseBody
    public AjaxJson copyThisInvoice(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            String id = request.getParameter("id");
            if (StringUtil.isNotEmpty(id)) {
                CbsDelinerEntity cbsDelinerEntity = systemService.getEntity(CbsDelinerEntity.class, id);
                if (StringUtil.isNotEmpty(cbsDelinerEntity)) {
                    CbsDelinerEntity cbsdeliver1 = new CbsDelinerEntity();
                    // 将旧发货单的数据复制给新的发货单
                    BeanUtils.copyProperties(cbsDelinerEntity, cbsdeliver1);

                    String uuid = getUuid();
                    cbsdeliver1.setId(uuid);

                    String cbsDeliverCode = cbsDelinerService.getDelinerCode();
                    cbsdeliver1.setCode(cbsDeliverCode);

                    cbsdeliver1.setStatus(StaticValue.CSAdfh);
                    cbsdeliver1.setCreateDate(new Date());
                    cbsdeliver1.setLogisticsSendTime(null);
                    cbsdeliver1.setCSASendTime(null);
                    cbsdeliver1.setExpectTime(null);
                    cbsdeliver1.setGetTime(null);
                    cbsdeliver1.setLogisticsDuration(0);
                    cbsdeliver1.setIsStandard(null);
                    cbsdeliver1.setQHTime(null);
                    cbsdeliver1.setLogisticsMemo(null);
                    cbsdeliver1.setSignMethod(null);
                    cbsdeliver1.setSignMemo(null);
                    cbsdeliver1.setNotQualified(null);
                    cbsdeliver1.setSignFile(null);
                    cbsdeliver1.setOffReason(null);
                    cbsdeliver1.setQxUser(null);
                    cbsdeliver1.setFhCSA(null);
                    cbsdeliver1.setIsHb(null);
                    cbsdeliver1.setLogisticsSendFile(null);
                    cbsdeliver1.setEtaStandard(null);
                    cbsdeliver1.setEtaQunqualified(null);
                    cbsdeliver1.setEtaNotQualifiedMemo(null);
                    cbsdeliver1.setSignStandard(null);
                    cbsDelinerService.save(cbsdeliver1);
                    ajaxJson.setSuccess(true);

//                    不克隆备件详情
//                    List<CbsDeliverEquipmentEntity> cbsDeliverEquipmentEntityList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id = '" + cbsDelinerEntity.getId() + "'");
//                    if (cbsDeliverEquipmentEntityList != null && cbsDeliverEquipmentEntityList.size() > 0) {
//                        for (int i = 0; i < cbsDeliverEquipmentEntityList.size(); i++) {
//                            CbsDeliverEquipmentEntity cbsDeliverEquipmentEntity = new CbsDeliverEquipmentEntity();
//                            BeanUtils.copyProperties(cbsDeliverEquipmentEntityList.get(i), cbsDeliverEquipmentEntity);
//                            String uuid1 = getUuid();
//                            cbsDeliverEquipmentEntity.setId(uuid1);
//                            cbsDeliverEquipmentEntity.setDeliverId(cbsdeliver1);
//                            cbsDeliverEquipmentEntity.setCreateDate(new Date());
//                            systemService.save(cbsDeliverEquipmentEntity);
//                        }
//                    }
                    //添加日志
                    cbsDelinerService.addDeliverLog("由" + cbsDelinerEntity.getCode() + "克隆生成", cbsdeliver1.getId(), 1);
                }
            }
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * 物流发货
     */
    @ResponseBody
    @RequestMapping(params = "WlSend")
    public AjaxJson WlSend(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map<String, Object> map = new HashMap<>();
        //获取登录的用户信息
        TSUser user = ResourceUtil.getSessionUserName();
        try {
            String id = request.getParameter("id");
            String bjh[] = request.getParameterValues("items");
            String[] sn = request.getParameterValues("sns");
            String code[] = request.getParameterValues("codes");
            String city[] = request.getParameterValues("citys"); //仓库
            String equipmentIds[] = request.getParameterValues("equipmentIds");
            String kw[] = request.getParameterValues("kws"); //库位
            String type = request.getParameter("type");
            CbsWarehouseEntity cbsWarehouseEntity = null;
            if (city != null) {
                cbsWarehouseEntity = systemService.singleResult("from CbsWarehouseEntity where name='" + city[0] + "'");
            }
            if (cbsWarehouseEntity != null) {
                systemService.updateBySqlString("update cbs_deliver set deliver_warehouse_id='" + cbsWarehouseEntity.getId() + "' where id = '" + id + "'");
            }

            String[] dh = request.getParameterValues("numbers");
            String[] weight = request.getParameterValues("weights");
            String time = request.getParameter("time"); /*预计到货时间*/
            String memo = request.getParameter("memo");
            String fileId = request.getParameter("fileId");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            String nowTime = sdf.format(date);
            StringBuffer stringBuffer = new StringBuffer();
            int i = systemService.updateBySqlString("update cbs_deliver set eta_standard = " + StaticValue.wdbETA + ",logistics_sendtime='" + nowTime + "',logistics_memo = '" + memo + "',expecttime='" + time + "',status='6' where id = '" + id + "'");
//
//          不知道哪个人挖的坑，物流修改了库位以后，不更改CSA选的库位
//          if (kw != null) {
//                systemService.updateBySqlString("update cbs_deliver set WAREHOUSE_POSITION = '" + kw[0] + "' where id = '" + id + "'");
//            }

            String etaQunqualified = request.getParameter("etaQunqualified");
            String etaNotQualifiedMemo = request.getParameter("etaNotQualifiedMemo");
            if (etaQunqualified != null) {
                systemService.updateBySqlString("update cbs_deliver set eta_standard = " + StaticValue.dbETA + ",eta_qunqualified='" + etaQunqualified + "',eta_not_qualified_memo='" + etaNotQualifiedMemo + "' where id = '" + id + "'");
            }
            if (i > 0) {
                /*添加预计到货时间日志*/
                cbsDelinerService.addDeliverLog(user.getRealName() + "填写预计到货时间：" + time, id, 2);

                if (bjh != null) {
                    for (int j = 0; j < bjh.length; j++) {
                        systemService.updateBySqlString("update cbs_deliver_equipment set item='" + bjh[j] + "',deliver_sn='" + sn[j] + "',WAREHOUSE_POSITION='" + kw[j] + "',logistics_number='" + dh[j] + "',weight='" + weight[j] + "',deliver_ercode = '" + code[j] + "' where id ='" + equipmentIds[j] + "'");
                    }
                }
            }
            if (StringUtil.isNotEmpty(type) && "app".equals(type)) {
                if (StringUtil.isNotEmpty(equipmentIds)) {
                    for (int j = 0; j < equipmentIds.length; j++) {
                        systemService.updateBySqlString("update cbs_deliver_equipment set deliver_sn='" + sn[j] + "',WAREHOUSE_POSITION='" + kw[j] + "',logistics_number='" + dh[j] + "' where id ='" + equipmentIds[j] + "'");
                    }
                }
                if (StringUtil.isNotEmpty(time)) {
                    System.out.println("update cbs_deliver set expecttime='" + time + " where id = '" + id + "'");
                    systemService.updateBySqlString("update cbs_deliver set expecttime='" + time + "' where id = '" + id + "'");

                    /*添加预计到货时间日志*/
                    cbsDelinerService.addDeliverLog("填写预计到货时间：" + time, id, 2);

                }
            }
            map.put("sta", 1);
            //记录操作日志
            CbsDelinerEntity cbsDeliner = systemService.get(CbsDelinerEntity.class, id);

            cbsDelinerService.addDeliverLog(user.getRealName() + "已发货", cbsDeliner.getId(), 2);
            //物流发货成功后通知服务工程师
            String phone = request.getParameter("cellPhone");
            CbsDelinerEntity cbsDelinerEntity = systemService.getEntity(CbsDelinerEntity.class, id);
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("crCode", StringUtil.isNotEmpty(cbsDelinerEntity.getCrCode()) ? cbsDelinerEntity.getCrCode() : "");
            paraMap.put("time", StringUtil.isNotEmpty(time) ? time : "");
            paraMap.put("code", StringUtil.isNotEmpty(cbsDelinerEntity.getCode()) ? cbsDelinerEntity.getCode() : "");
            if (phone != null && !phone.equals("")) {
                SendMessage.sendSMSFTL(phone, "message_send_wlsend.ftl", paraMap, systemService);
            }
            if (cbsDelinerEntity.getPhone() != null) {
                SendMessage.sendSMSFTL(cbsDelinerEntity.getPhone(), "message_send_sms_shou.ftl", paraMap, systemService);
            }
            String crCode = "";
            String logisticsNumber = "";
            List<CbsDeliverEquipmentEntity> cde = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + cbsDeliner.getId() + "'");
            if (cde != null && cde.size() > 0) {
                logisticsNumber = cde.get(0).getLogisticsNumber();
            }
            CbsServiceEntity service = systemService.singleResult("from CbsServiceEntity where code ='" + cbsDeliner.getCrCode() + "'");
            String emailTitle = "物流发货通知：<" + cbsDeliner.getCode() + ">-<" + (StringUtil.isNotEmpty(cbsDeliner.getCrCode()) ? cbsDeliner.getCrCode() : "") + ">-<" + cbsDeliner.getCinemaName() + ">" + getDateStr(new Date());
            String emailContent = "您的发货单<" + cbsDeliner.getCode() + ">已发货，预计到货时间为<" + cbsDeliner.getExpectTime() + ">， 物流单号：<" + logisticsNumber + ">。\n" +
                    "具体内容请查看http://cbs.cfg-barco.com或登陆巴可客服App。\n" +
                    "【中影巴可客服部】\n" +
                    "* 该邮件请勿回复";
            //邮件通知csa
            if (cbsDeliner.getFhCSA() != null && cbsDeliner.getFhCSA().getEmail() != null && !cbsDeliner.getFhCSA().getEmail().equals("")) {
                SendMailUtil.sendeMail(cbsDeliner.getFhCSA().getEmail(), emailTitle, emailContent, systemService);
            }
            //邮件通知备件申请人
            if (cbsDeliner.getEquipmentApplyId() != null && cbsDeliner.getEquipmentApplyId().getCreateBy() != null) {
                TSUser eqAppUser = systemService.singleResult("from TSUser where userName='" + cbsDeliner.getEquipmentApplyId().getCreateBy() + "'");
                if (eqAppUser != null && eqAppUser.getEmail() != null && !eqAppUser.getEmail().equals("")) {
                    SendMailUtil.sendeMail(eqAppUser.getEmail(), emailTitle, emailContent, systemService);
                }
            }


            if (cbsDelinerEntity != null) {
                String msContent = null;
                msContent = "尊敬的客户：您的服务单<" + (StringUtil.isNotEmpty(cbsDeliner.getCrCode()) ? cbsDeliner.getCrCode() : "") + ">申请的备件物流已经安排发货，请您保持联系方式畅通，并妥善签收备件。【中影巴可客服部】";
                System.out.println(msContent);
                //微信通知收货人
                System.out.println("---------------");
                List<TSUser> wxUserList = systemService.findHql("from TSUser where mobilePhone='" + cbsDeliner.getPhone() + "'");
                if (wxUserList != null && wxUserList.size() > 0 && wxUserList.get(0) != null) {
                    String openId = wxUserList.get(0).getOpenId();
                    if (StringUtil.isNotEmpty(openId)) {
                        /*发送微信提醒*/
                        //调用微信接口发送
                        List<Map<String, String>> list = new ArrayList<>();
                        if (StringUtil.isNotEmpty(openId)) {
                            Map<String, String> map1 = new HashMap<>();
                            map1.put("openid", openId);
                            map1.put("message", msContent);
                            list.add(map1);
                            wxCommonService.sendMsgForWx(list);
                        }
                    }
                }
            }
        } catch (Exception e) {
            map.put("sta", 0);
            e.getMessage();

        }
        ajaxJson.setAttributes(map);
        return ajaxJson;
    }

    /**
     * 上传附件功能
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "uploadFile")
    public AjaxJson fileUploadView(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        Map<String, Object> attributes = new HashMap<String, Object>();
        String cbsServiceId = oConvertUtils.getString(request.getParameter("cbsDeliverId"));
        String businessType = request.getParameter("businessType");
        if (cbsServiceId != null && cbsServiceId != "") {
            FileBean fileBean = UploadFileUtil.UploadFile(request);
            if (StringUtil.isNotEmpty(cbsServiceId)) {
                ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
                zyfileLog.setBusinessKey(cbsServiceId);
                zyfileLog.setFilePath(fileBean.getSavePath());
                zyfileLog.setOldFileName(fileBean.getFileRealName());
                zyfileLog.setNewFileName(fileBean.getFileName());
                zyfileLog.setCreateDate(new Date());
                zyfileLog.setCreateDate(new Date());
                if ("F".equals(businessType)) {
                    zyfileLog.setBusinessType("F");
                }
                if ("S".equals(businessType)) {
                    zyfileLog.setBusinessType("S");
                }
                if ("L".equals(businessType)) {
                    zyfileLog.setBusinessType("L");
                }
//                zyfileLog.setBusinessType(StaticValue.FILE_SERVICE_OFFER_TYPE_DATA);
//                zyfileLog.setBusinessChildType("A");
                systemService.save(zyfileLog);
            }
            String id = null;
            Map<String, Object> fileLogMap = systemService.findOneForJdbc("SELECT t.id FROM zy_file_log t where  t.business_key = '" + cbsServiceId + "' and old_file_name = '" + fileBean.getFileRealName() + "'order by t.create_date desc limit 1 ");
            if (fileLogMap != null) {
                id = fileLogMap.get("id").toString();
            }
            attributes.put("name", fileBean.getFileRealName());
            attributes.put("id", id);
            j.setAttributes(attributes);
        }
        return j;
    }

    /**
     * 合并发货
     *
     * @return
     */
    @RequestMapping(params = "sendTogether")
    public ModelAndView sendTogether(String ids, HttpServletRequest request) {
        List<CbsDelinerEntity> cbsDelinerEntityList = new ArrayList<>();
        List<CbsDeliverEquipmentEntity> cbsDeliverEquipmentEntityList = null;
        List<CbsDeliverEquipmentEntity> cbsDeliverEquipmentEntityList2 = new ArrayList<>();
        List<String> stringList = new ArrayList<>();
        List<TSTerritory> territoryList = null;
        CbsDelinerEntity cbsDeliner = null;
        try {
            for (String id : ids.split(",")) {
                cbsDeliner = systemService.getEntity(CbsDelinerEntity.class, id);
                cbsDeliverEquipmentEntityList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + id + "'");
                cbsDelinerEntityList.add(cbsDeliner);
                cbsDeliverEquipmentEntityList2.addAll(cbsDeliverEquipmentEntityList);
            }
            for (int i = 0; i < cbsDeliverEquipmentEntityList2.size(); i++) {
                CbsDeliverEquipmentEntity cbsDeliverEquipmentEntity = cbsDeliverEquipmentEntityList2.get(i);
//				if (cbsDeliverEquipmentEntity.getIsReturn()==2){
                stringList.add(cbsDeliverEquipmentEntity.getId());
//				}
            }
            request.setAttribute("ids", ids);
            request.setAttribute("stringList", stringList);
            request.setAttribute("cbsDeliverEquipmentEntityList2", cbsDeliverEquipmentEntityList2);
            request.setAttribute("cbsDelinerEntity", cbsDelinerEntityList.get(0));
            String hql = "from CbsDelinerEntity where id ='" + cbsDelinerEntityList.get(0).getId() + "'";
            CbsDelinerEntity cbsDelinerEntity = systemService.singleResult(hql);
            if (cbsDelinerEntity.getShi() != null) {
                List<CbsWarehouseEntity> cbsWarehouseEntityList = systemService.findHql("from CbsWarehouseEntity where shi.id='" + cbsDelinerEntity.getShi().getId() + "' and isClose='0'");
                if (cbsWarehouseEntityList.size() > 0) {
                    request.setAttribute("cbsWarehouseEntityList", cbsWarehouseEntityList.get(0).getLogistics());
                }
            }


            if (cbsDelinerEntity.getDeliverWarehouseId() != null) {
                String hql1 = "from CbsWarehouseEntity where id='" + cbsDelinerEntity.getDeliverWarehouseId().getId() + "' and isClose='0'  group by logistics";
                List<CbsWarehouseEntity> cbsWarehouseList = systemService.findHql(hql1);
                if (cbsWarehouseList.size() > 0) {
                    request.setAttribute("logisticsName", cbsWarehouseList.get(0).getLogistics());
                }
            }

            territoryList = systemService.findHql("from TSTerritory where territoryLevel = 1 order by territorySort");
            List<CbsWarehouseEntity> cbsWarehouseEntities = systemService.findHql("from CbsWarehouseEntity where isClose = '0'");
            request.setAttribute("territoryList", territoryList);
            request.setAttribute("cbsWarehouseEntities", cbsWarehouseEntities);
            if (cbsDelinerEntity.getShi() != null) {
                List<CbsWarehouseEntity> cbsWarehouseEntityList1 = systemService.findHql("from CbsWarehouseEntity where shi.id='" + cbsDelinerEntity.getShi().getId() + "' and isClose='0'");
                if (cbsWarehouseEntityList1.size() > 0) {
                    request.setAttribute("cbsWarehouseEntity", cbsWarehouseEntityList1.get(0));
                }
            }

            System.out.println(cbsDelinerEntityList);
            List<TSType> types = systemService.findHql("from TSType where TSTypegroup.typegroupcode='kuwei'");
            request.setAttribute("types", types);
            List<TSType> fhSLAs = systemService.findHql("from TSType where TSTypegroup.typegroupcode='fhSLA'");
            request.setAttribute("fhSLAs", fhSLAs);
            //查询物流
            String hhql = "from TSDepart where orgType='logistics' and logicDelete = '0'";
            List<TSDepart> tsDepartList = systemService.findHql(hhql);
            request.setAttribute("tsDepartList", tsDepartList);
            if (cbsDelinerEntity.getDeliverWarehouseId() != null) {
                List<CbsWarehouseEntity> CbsWarehouseEntitys = systemService.findHql("from CbsWarehouseEntity where id='" + cbsDelinerEntity.getDeliverWarehouseId().getId() + "' and isClose='0'");
                if (CbsWarehouseEntitys.size() > 0) {
                    request.setAttribute("warehouseName", CbsWarehouseEntitys.get(0).getName());
                }
            }

            //根据发货物流获取对应的联系人
            TSDepart tsDepart = null;
            List<ZyContactsEntity> zyContacts = null;
            if (cbsDeliner.getDeliverLogistics() != null && cbsDeliner.getDeliverLogistics() != "") {
                tsDepart = systemService.singleResult("from TSDepart where departname='" + cbsDeliner.getDeliverLogistics() + "' and orgType='logistics'");
                zyContacts = systemService.findHql("from ZyContactsEntity where belongOrg.id='" + tsDepart.getId() + "'");
                if (zyContacts != null && zyContacts.size() > 0) {
                    request.setAttribute("zyContacts", zyContacts.get(0));
                } else {
                    request.setAttribute("zyContacts", null);
                }
            }


            //根据返件物流获取对应的联系人
            TSDepart tsDepart2 = systemService.singleResult("from TSDepart where departname='" + cbsDeliner.getReturnLogistics() + "' and orgType='logistics'");
            if (tsDepart2 != null) {
                List<ZyContactsEntity> returnContacts = systemService.findHql("from ZyContactsEntity where belongOrg.id='" + tsDepart2.getId() + "'");
                if (returnContacts != null && returnContacts.size() > 0) {
                    request.setAttribute("returnContacts", returnContacts.get(0));
                } else {
                    request.setAttribute("returnContacts", null);
                }
            }
            if (cbsDeliner.getDeliverLogistics() != null && !cbsDeliner.getDeliverLogistics().equals("")) {
                String sql = "SELECT\n" +
                        "\tcw.name as name,\n" +
                        "\tcw.id as id,cw.user_name AS userName,cw.phone AS phone,cw.email AS email\n" +
                        "FROM\n" +
                        "\tcbs_warehouse cw\n" +
                        "WHERE\n" +
                        "\tcw.is_close = '0'\n" +
                        "and cw.logistics = '" + cbsDeliner.getDeliverLogistics() + "'\n";
                List<Map<String, Object>> wareList = systemService.findForJdbc(sql);
                request.setAttribute("wareList", wareList);
            } else {
                List<Map<String, Object>> wareList = systemService.findForJdbc("select cw.name as name,cw.id as id from cbs_warehouse cw");
                request.setAttribute("wareList", wareList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
        return new ModelAndView("com/zybk/cbs_deliver/CSAHBdeliver");
    }

    /**
     * 根据备件类型查询备件号
     */
    @RequestMapping(params = "getItemsByType")
    @ResponseBody
    public AjaxJson getItemsByType(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String typeId = request.getParameter("typeId");
        List<ZyEsItemEntity> zyEsItemEntityList = systemService.findHql("from ZyEsItemEntity where type.id='" + typeId + "'");
        ajaxJson.setObj(zyEsItemEntityList);
        return ajaxJson;
    }

    /**
     * 发货单详情页根据备件类型查询备件号
     */
    @RequestMapping(params = "getItemByType")
    @ResponseBody
    public AjaxJson getItemByType(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map<String, Object> map = new HashMap<>();

        String equipment = request.getParameter("equipment");
        JSONArray json = JSONArray.fromObject(equipment);
        System.out.println("json:" + json);
        JSONObject jsonOne;
        for (int i = 0; i < json.size(); i++) {
            jsonOne = json.getJSONObject(i);
            String eqId = jsonOne.getString("equipmentId");
            String typeId = jsonOne.getString("equipmentType");
            List<ZyEsItemEntity> zyEsItemEntityList = systemService.findHql("from ZyEsItemEntity where type.id='" + typeId + "'");
            map.put(eqId, zyEsItemEntityList);
        }
        ajaxJson.setAttributes(map);
        return ajaxJson;
    }

    /**
     * 物流发货跳转页
     */
    @RequestMapping(params = "sendLogistics")
    public ModelAndView sendLogistics(HttpServletRequest request) {
        String id = request.getParameter("id");
        String reason = request.getParameter("reason");
        CbsDelinerEntity entity = null;
        if (StringUtil.isNotEmpty(id)) {
            entity = systemService.getEntity(CbsDelinerEntity.class, id);
            request.setAttribute("cbsDelinerPage", entity);
            List<CbsDelinerEntity> cbsDelinerEntityList = systemService.findHql("from CbsDelinerEntity where id = '" + id + "' ");
            if (cbsDelinerEntityList.size() > 0) {
                request.setAttribute("cbsDelinerEntityList", cbsDelinerEntityList.get(0));
            }
            if (entity != null) {
                if (entity.getSignFile() != null) {
                    ZyFileLogEntity zyFileLogEntity = systemService.getEntity(ZyFileLogEntity.class, entity.getSignFile());
                    request.setAttribute("zyFileLogEntity", zyFileLogEntity);
                }
            }
        }
        List<TSType> etaStandardList = systemService.findHql("FROM TSType where TSTypegroup.typegroupcode='etaStandard'");
        request.setAttribute("etaStandardList", etaStandardList);
        Integer slaType = null;
        if (entity.getWlSLA() != null && entity.getWlSLA() != "") {
            if (entity.getWlSLA().equals("SL1")) {
                slaType = 1;
            } else if (entity.getWlSLA().equals("SL2")) {
                slaType = 2;
            } else if (entity.getWlSLA().equals("SL3")) {
                slaType = 3;
            } else if (entity.getWlSLA().equals("SL4")) {
                slaType = 4;
            } else if (entity.getWlSLA() == null) {
                slaType = 10;
            } else if (entity.getWlSLA().equals("无")) {
                slaType = 10;
            }
            request.setAttribute("slaType", slaType);
        } else {
            request.setAttribute("slaType", 10);
        }
        if (entity != null) {
            String hql = "from CbsServiceEntity where code='" + entity.getCrCode() + "'";
            List<CbsServiceEntity> cbsServiceEntity = systemService.findHql(hql);
            if (StringUtil.isNotEmpty(cbsServiceEntity) && cbsServiceEntity.size() > 0) {
                request.setAttribute("cbsServiceEntity", cbsServiceEntity.get(0));
            }
            List<Map<String, Object>> list = new ArrayList();
            Map map = new HashMap();
            if (entity.getIsHb() != null && entity.getIsHb().equals("1")) {
                if (entity.getSpaceNumber() != null && entity.getSpaceNumber() != "") {
                    String[] split = entity.getSpaceNumber().split("/");
                    for (int i = 0; i < split.length; i++) {
                        CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.singleResult("from CbsEquipmentApplyEntity where recordId = '" + split[i] + "'");
                        if (cbsEquipmentApplyEntity != null) {
                            map.put("name", cbsEquipmentApplyEntity.getCreateName());
                            //申请人电话
                            List<String> mobilePhone = systemService.findListbySql("select mobilePhone from t_s_user where id=(select id from t_s_base_user where username='" + cbsEquipmentApplyEntity.getCreateBy() + "')");
                            if (mobilePhone != null && mobilePhone.size() > 0) {
                                map.put("phone", mobilePhone);
                            }
                            //获取服务商信息
                            List<String> shortname = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + cbsEquipmentApplyEntity.getServiceId() + "'");
                            if (shortname.size() != 0) {
                                map.put("shortname", shortname.get(0));
                            }
                            list.add(map);
                        }
                    }
                }

                if (list != null && list.size() > 0) {
                    request.setAttribute("list", list);
                } else {
                    request.setAttribute("list", null);
                }
                request.setAttribute("Hb", "1");
            } else {
                if (entity.getEquipmentApplyId() != null) {
                    CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.getEntity(CbsEquipmentApplyEntity.class, entity.getEquipmentApplyId().getId());
                    request.setAttribute("cbsEquipmentApplyEntity", cbsEquipmentApplyEntity);
                    //申请人电话
                    List<String> mobilePhone = systemService.findListbySql("select mobilePhone from t_s_user where id=(select id from t_s_base_user where username='" + cbsEquipmentApplyEntity.getCreateBy() + "')");
                    if (mobilePhone != null && mobilePhone.size() > 0) {
                        request.setAttribute("mobilePhone", mobilePhone);
                    }
                    //获取服务商信息
                    List<String> shortname = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + cbsEquipmentApplyEntity.getServiceId() + "'");
                    if (shortname.size() != 0) {
                        request.setAttribute("shortname", shortname.get(0));
                    }
                }
                request.setAttribute("Hb", "2");
            }
            if (StringUtil.isNotEmpty(cbsServiceEntity) && cbsServiceEntity.size() > 0) {
                String hql1 = "select * FROM cbs_service_assign_list WHERE service_id='" + cbsServiceEntity.get(0).getId() + "' AND assign_torole in(2,3) AND status NOT in(2,4) ORDER BY create_date DESC LIMIT 1";
                Map<String, Object> assignMap = systemService.findOneForJdbc(hql1);
                if (assignMap != null) {
                    String engineerId = (String) assignMap.get("assign_touser");
                    ZyEngineerEntity engineer = systemService.get(ZyEngineerEntity.class, engineerId);
                    request.setAttribute("engineer", engineer);
                }
            }
        }//获取服务工程师信息
        List<ZyFileLogEntity> zyFileLogEntityList = systemService.findHql("from ZyFileLogEntity where businessKey = '" + entity.getId() + "' and businessType = 'L'");
        if (zyFileLogEntityList != null && zyFileLogEntityList.size() > 0) {
            request.setAttribute("zyFileLogEntityList", zyFileLogEntityList);
        } else {
            request.setAttribute("zyFileLogEntityList", null);
        }
        List<ZyFileLogEntity> zyFileLogEntityListSign = systemService.findHql("from ZyFileLogEntity where businessKey = '" + entity.getId() + "' and businessType = 'S'");
        if (zyFileLogEntityListSign != null && zyFileLogEntityListSign.size() > 0) {
            request.setAttribute("zyFileLogEntityListSign", zyFileLogEntityListSign);
        } else {
            request.setAttribute("zyFileLogEntityListSign", null);
        }
        //获取发货单状态
        TSType deliverStatus = systemService.singleResult("from TSType where typecode='" + entity.getStatus() + "'and TSTypegroup.typegroupcode='deliver_status'");
        request.setAttribute("deliverStatus", deliverStatus);

        //获取发货sla
        TSType fhSLA = systemService.singleResult("from TSType where typecode='" + entity.getFhSLA() + "' and TSTypegroup.typegroupcode='fhSLA'");
        request.setAttribute("fhSLA", fhSLA);
        //根据发货单号获取申请的备件
        List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + entity.getId() + "'");
        request.setAttribute("deliverEquipmentList", deliverEquipmentList);
        //获取申请优先级
        List<TSType> applyLayerList = systemService.findHql("from TSType where TSTypegroup.typegroupcode='apply_layer'");
        request.setAttribute("applyLayerList", applyLayerList);
        List<ZyEsItemEntity> zyEsItemEntitys = systemService.findHql("from ZyEsItemEntity");
        request.setAttribute("zyEsItemEntitys", zyEsItemEntitys);
        List<TSType> types = systemService.findHql("from TSType where TSTypegroup.typegroupcode='kuwei'");
        request.setAttribute("types", types);

        //获取所有的发货单类型
        String hql = "from TSType where TSTypegroup.typegroupcode='Deliver_Type'";
        List<TSType> deliverTypeList = systemService.findHql(hql);
        request.setAttribute("deliverTypeList", deliverTypeList);
        
        //查询分派到物流以后的发货单操作日志
        List<CbsHandleLogEntity> logisticsLogList = systemService.findHql("from CbsHandleLogEntity where logType=2 and businessId='" + entity.getId() + "' and processStatus=2  ORDER BY createDate DESC");
        request.setAttribute("logisticsLogList", logisticsLogList);
        if ("XG".equals(reason)) {
            return new ModelAndView("com/zybk/cbs_deliver/sendLogistics_changeTime");
        } else if ("CK".equals(reason)) {
            return new ModelAndView("com/zybk/cbs_deliver/sendLogistics_details");
        } else {
            return new ModelAndView("com/zybk/cbs_deliver/sendLogistics");
        }
    }

    /**
     * 物流发货跳转详情页
     */
    @RequestMapping(params = "sendDetails")
    public ModelAndView sendDetails(HttpServletRequest request) {
        String id = request.getParameter("id");
        String reason = request.getParameter("reason");
        CbsDelinerEntity entity = null;
        List<TSType> etaStandardList = systemService.findHql("FROM TSType where TSTypegroup.typegroupcode='etaStandard'");
        request.setAttribute("etaStandardList", etaStandardList);
        if (StringUtil.isNotEmpty(id)) {
            entity = systemService.getEntity(CbsDelinerEntity.class, id);
            request.setAttribute("cbsDelinerPage", entity);
            List<CbsDelinerEntity> cbsDelinerEntityList = systemService.findHql("from CbsDelinerEntity where id = '" + id + "' ");
            if (cbsDelinerEntityList.size() > 0) {
                request.setAttribute("cbsDelinerEntityList", cbsDelinerEntityList.get(0));
            }
            if (entity != null) {
                if (entity.getSignFile() != null) {
                    ZyFileLogEntity zyFileLogEntity = systemService.getEntity(ZyFileLogEntity.class, entity.getSignFile());
                    request.setAttribute("zyFileLogEntity", zyFileLogEntity);
                }
            }
        }
        if (entity != null) {
            String hql = "from CbsServiceEntity where code='" + entity.getCrCode() + "'";
            CbsServiceEntity cbsServiceEntity = systemService.singleResult(hql);
            request.setAttribute("cbsServiceEntity", cbsServiceEntity);
            List<Map<String, Object>> list = new ArrayList();
            Map map = new HashMap();
            if (entity.getIsHb() != null && entity.getIsHb().equals("1")) {
                if (entity.getSpaceNumber() != null && entity.getSpaceNumber() != "") {
                    String[] split = entity.getSpaceNumber().split("/");
                    for (int i = 0; i < split.length; i++) {
                        CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.singleResult("from CbsEquipmentApplyEntity where recordId = '" + split[i] + "'");
                        if (cbsEquipmentApplyEntity != null) {
                            map.put("name", cbsEquipmentApplyEntity.getCreateName());
                            //申请人电话
                            List<String> mobilePhone = systemService.findListbySql("select mobilePhone from t_s_user where id=(select id from t_s_base_user where username='" + cbsEquipmentApplyEntity.getCreateBy() + "')");
                            if (mobilePhone != null && mobilePhone.size() > 0) {
                                map.put("phone", mobilePhone);
                            }
                            //获取服务商信息
                            List<String> shortname = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + cbsEquipmentApplyEntity.getServiceId() + "'");
                            if (shortname.size() != 0) {
                                map.put("shortname", shortname.get(0));
                            }
                            list.add(map);
                        }
                    }
                }

                if (list != null && list.size() > 0) {
                    request.setAttribute("list", list);
                } else {
                    request.setAttribute("list", null);
                }
                request.setAttribute("Hb", "1");
            } else {
                if (entity.getEquipmentApplyId() != null) {
                    CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.getEntity(CbsEquipmentApplyEntity.class, entity.getEquipmentApplyId().getId());
                    request.setAttribute("cbsEquipmentApplyEntity", cbsEquipmentApplyEntity);
                    //申请人电话
                    List<String> mobilePhone = systemService.findListbySql("select mobilePhone from t_s_user where id=(select id from t_s_base_user where username='" + cbsEquipmentApplyEntity.getCreateBy() + "')");
                    if (mobilePhone != null && mobilePhone.size() > 0) {
                        request.setAttribute("mobilePhone", mobilePhone);
                    }
                    //获取服务商信息
                    List<String> shortname = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + cbsEquipmentApplyEntity.getServiceId() + "'");
                    if (shortname.size() != 0) {
                        request.setAttribute("shortname", shortname.get(0));
                    }
                }
                request.setAttribute("Hb", "2");
            }

            if (cbsServiceEntity != null) {
                String hql1 = "select * FROM cbs_service_assign_list WHERE service_id='" + cbsServiceEntity.getId() + "' AND assign_torole in(2,3) AND status NOT in(2,4) ORDER BY create_date DESC LIMIT 1";
                Map<String, Object> assignMap = systemService.findOneForJdbc(hql1);
                if (assignMap != null) {
                    String engineerId = (String) assignMap.get("assign_touser");
                    ZyEngineerEntity engineer = systemService.get(ZyEngineerEntity.class, engineerId);
                    request.setAttribute("engineer", engineer);
                }
            }
        }//获取备件申请人信息
        List<ZyFileLogEntity> zyFileLogEntityList = systemService.findHql("from ZyFileLogEntity where businessKey = '" + entity.getId() + "' and businessType = 'L'");
        if (zyFileLogEntityList != null && zyFileLogEntityList.size() > 0) {
            request.setAttribute("zyFileLogEntityList", zyFileLogEntityList);
        } else {
            request.setAttribute("zyFileLogEntityList", null);
        }
        List<ZyFileLogEntity> zyFileLogEntityListSign = systemService.findHql("from ZyFileLogEntity where businessKey = '" + entity.getId() + "' and businessType = 'S'");
        if (zyFileLogEntityListSign != null && zyFileLogEntityListSign.size() > 0) {
            request.setAttribute("zyFileLogEntityListSign", zyFileLogEntityListSign);
        } else {
            request.setAttribute("zyFileLogEntityListSign", null);
        }
        //获取发货单状态
        TSType deliverStatus = systemService.singleResult("from TSType where typecode='" + entity.getStatus() + "'and TSTypegroup.typegroupcode='deliver_status'");
        request.setAttribute("deliverStatus", deliverStatus);

        //获取发货sla
        TSType fhSLA = systemService.singleResult("from TSType where typecode='" + entity.getFhSLA() + "' and TSTypegroup.typegroupcode='fhSLA'");
        request.setAttribute("fhSLA", fhSLA);
        //根据发货单号获取申请的备件
        List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + entity.getId() + "'");
        request.setAttribute("deliverEquipmentList", deliverEquipmentList);
        //获取申请优先级
        List<TSType> applyLayerList = systemService.findHql("from TSType where TSTypegroup.typegroupcode='apply_layer'");
        request.setAttribute("applyLayerList", applyLayerList);
        List<ZyEsItemEntity> zyEsItemEntitys = systemService.findHql("from ZyEsItemEntity");
        request.setAttribute("zyEsItemEntitys", zyEsItemEntitys);
        List<TSType> types = systemService.findHql("from TSType where TSTypegroup.typegroupcode='kuwei'");
        request.setAttribute("types", types);

        //获取所有的发货单类型
        String hql = "from TSType where TSTypegroup.typegroupcode='Deliver_Type'";
        List<TSType> deliverTypeList = systemService.findHql(hql);
        request.setAttribute("deliverTypeList", deliverTypeList);
        
        //查询分派到物流以后的发货单操作日志
        List<CbsHandleLogEntity> logisticsLogList = systemService.findHql("from CbsHandleLogEntity where logType=2 and businessId='" + entity.getId() + "' and processStatus=2  ORDER BY createDate DESC");
        request.setAttribute("logisticsLogList", logisticsLogList);
        if ("sign".equals(reason)) {
            return new ModelAndView("com/zybk/cbs_deliver/cbsDeliver-sign_details");
        } else {
            return new ModelAndView("com/zybk/cbs_deliver/sendLogistics_details");
        }
    }

    /**
     * 物流签收跳转页
     */
    @RequestMapping(params = "sendSign")
    public ModelAndView sendSign(HttpServletRequest request) {
        String id = request.getParameter("id");
        CbsDelinerEntity entity = null;
        if (StringUtil.isNotEmpty(id)) {
            entity = systemService.getEntity(CbsDelinerEntity.class, id);
            request.setAttribute("cbsDelinerPage", entity);
            Integer slaType = null;
            if (entity.getWlSLA() != null && entity.getWlSLA() != "") {
                if (entity.getWlSLA().equals("SL1")) {
                    slaType = 1;
                } else if (entity.getWlSLA().equals("SL2")) {
                    slaType = 2;
                } else if (entity.getWlSLA().equals("SL3")) {
                    slaType = 3;
                } else if (entity.getWlSLA().equals("SL4")) {
                    slaType = 4;
                } else if (entity.getWlSLA() == null) {
                    slaType = 10;
                } else if (entity.getWlSLA().equals("无")) {
                    slaType = 10;
                }
                request.setAttribute("slaType", slaType);
            } else {
                request.setAttribute("slaType", 10);
            }
            List<TSType> sendReasonList = systemService.findHql("FROM TSType where TSTypegroup.typegroupcode='send_reason'");
            request.setAttribute("sendReasonList", sendReasonList);
            List<TSType> signTypeList = systemService.findHql("FROM TSType where TSTypegroup.typegroupcode='signType'");
            request.setAttribute("signTypeList", signTypeList);
            if (entity.getSignFile() != null && entity.getSignFile() != "") {
                ZyFileLogEntity zyFileLogEntity = systemService.singleResult("from ZyFileLogEntity where id = '" + entity.getSignFile() + "'");
                request.setAttribute("zyFileLogEntity", zyFileLogEntity);
            }
            //获取发货单状态
            TSType deliverStatus = systemService.singleResult("from TSType where typecode='" + entity.getStatus() + "'and TSTypegroup.typegroupcode='deliver_status'");
            request.setAttribute("deliverStatus", deliverStatus);
            List<TSType> tsTypes = systemService.findHql("FROM TSType where TSTypegroup.typegroupcode='kuwei'");
            request.setAttribute("types", tsTypes);
            //获取所有的发货单类型
            String hqlType = "from TSType where TSTypegroup.typegroupcode='Deliver_Type'";
            List<TSType> deliverTypeList = systemService.findHql(hqlType);
            request.setAttribute("deliverTypeList", deliverTypeList);
            //获取备件申请人信息
            if (entity != null) {
                String hql = "from CbsServiceEntity where code='" + entity.getCrCode() + "'";
                CbsServiceEntity cbsServiceEntity = systemService.singleResult(hql);
                request.setAttribute("cbsServiceEntity", cbsServiceEntity);
                List<Map<String, Object>> list = new ArrayList();
                Map map = new HashMap();
                if (entity.getIsHb() != null && entity.getIsHb().equals("1")) {
                    if (entity.getSpaceNumber() != null && entity.getSpaceNumber() != "") {
                        String[] split = entity.getSpaceNumber().split("/");
                        for (int i = 0; i < split.length; i++) {
                            CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.singleResult("from CbsEquipmentApplyEntity where recordId = '" + split[i] + "'");
                            if (cbsEquipmentApplyEntity != null) {
                                map.put("name", cbsEquipmentApplyEntity.getCreateName());
                                //申请人电话
                                List<String> mobilePhone = systemService.findListbySql("select mobilePhone from t_s_user where id=(select id from t_s_base_user where username='" + cbsEquipmentApplyEntity.getCreateBy() + "')");
                                if (mobilePhone != null && mobilePhone.size() > 0) {
                                    map.put("phone", mobilePhone);
                                }
                                //获取服务商信息
                                List<String> shortname = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + cbsEquipmentApplyEntity.getServiceId() + "'");
                                if (shortname.size() != 0) {
                                    map.put("shortname", shortname.get(0));
                                }
                                list.add(map);
                            }
                        }
                    }

                    if (list != null && list.size() > 0) {
                        request.setAttribute("list", list);
                    } else {
                        request.setAttribute("list", null);
                    }
                    request.setAttribute("Hb", "1");
                } else {
                    if (entity.getEquipmentApplyId() != null) {
                        CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.getEntity(CbsEquipmentApplyEntity.class, entity.getEquipmentApplyId().getId());
                        request.setAttribute("cbsEquipmentApplyEntity", cbsEquipmentApplyEntity);
                        //申请人电话
                        List<String> mobilePhone = systemService.findListbySql("select mobilePhone from t_s_user where id=(select id from t_s_base_user where username='" + cbsEquipmentApplyEntity.getCreateBy() + "')");
                        if (mobilePhone != null && mobilePhone.size() > 0) {
                            request.setAttribute("mobilePhone", mobilePhone);
                        }
                        //获取服务商信息
                        List<String> shortname = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + cbsEquipmentApplyEntity.getServiceId() + "'");
                        if (shortname.size() != 0) {
                            request.setAttribute("shortname", shortname.get(0));
                        }
                    }
                    request.setAttribute("Hb", "2");
                }
                //获取该服务单类型是否是引擎翻新
                if (cbsServiceEntity != null && cbsServiceEntity.getServiceType2() != null) {
                    if (cbsServiceEntity.getServiceType2().getName().equals("引擎翻新")) {
                        request.setAttribute("yqfx", 1);
                    }
                }

                if (cbsServiceEntity != null) {
                    String hql1 = "select * FROM cbs_service_assign_list WHERE service_id='" + cbsServiceEntity.getId() + "' AND assign_torole in(2,3) AND status NOT in(2,4) ORDER BY create_date DESC LIMIT 1";
                    Map<String, Object> assignMap = systemService.findOneForJdbc(hql1);
                    if (assignMap != null) {
                        String engineerId = (String) assignMap.get("assign_touser");
                        ZyEngineerEntity engineer = systemService.get(ZyEngineerEntity.class, engineerId);
                        request.setAttribute("engineer", engineer);
                    }
                }
            }

        }
        //获取发货sla
        TSType fhSLA = systemService.singleResult("from TSType where typecode='" + entity.getFhSLA() + "' and TSTypegroup.typegroupcode='fhSLA'");
        request.setAttribute("fhSLA", fhSLA);
        //根据发货单号获取申请的备件
        List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + entity.getId() + "'");
        request.setAttribute("deliverEquipmentList", deliverEquipmentList);
        List<ZyEsItemEntity> zyEsItemEntitys = systemService.findHql("from ZyEsItemEntity");
        request.setAttribute("zyEsItemEntitys", zyEsItemEntitys);
        List<TSType> types = systemService.findHql("from TSType where TSTypegroup.typegroupcode='kuwei'");
        request.setAttribute("types", types);
        // CbsEquipmentApplyDetailEntity cbsEquipmentApplyDetailEntity = systemService.getEntity(CbsEquipmentApplyDetailEntity.class, "402881e6614135a10161413b32df0008");
        List<ZyFileLogEntity> zyFileLogEntityList = systemService.findHql("from ZyFileLogEntity where businessKey = '" + entity.getId() + "' and businessType = 'S'");
        if (zyFileLogEntityList != null && zyFileLogEntityList.size() > 0) {
            request.setAttribute("zyFileLogEntityList", zyFileLogEntityList);
        } else {
            request.setAttribute("zyFileLogEntityList", null);
        }
        List<ZyFileLogEntity> zyFileLogEntityListSend = systemService.findHql("from ZyFileLogEntity where businessKey = '" + entity.getId() + "' and businessType = 'L'");
        if (zyFileLogEntityListSend != null && zyFileLogEntityListSend.size() > 0) {
            request.setAttribute("zyFileLogEntityListSend", zyFileLogEntityListSend);
        } else {
            request.setAttribute("zyFileLogEntityListSend", null);
        }
        //查询分派到物流以后的发货单操作日志
        List<CbsHandleLogEntity> logisticsLogList = systemService.findHql("from CbsHandleLogEntity where logType=2 and businessId='" + entity.getId() + "' and processStatus=2  ORDER BY createDate DESC");
        request.setAttribute("logisticsLogList", logisticsLogList);
        return new ModelAndView("com/zybk/cbs_deliver/cbsDeliver-sign");
    }

    /**
     * 物流签收跳转详情页
     */
    @RequestMapping(params = "sendSignDetails")
    public ModelAndView sendSignDetails(HttpServletRequest request) {
        String id = request.getParameter("id");
        CbsDelinerEntity entity = null;
        if (StringUtil.isNotEmpty(id)) {
            entity = systemService.getEntity(CbsDelinerEntity.class, id);
            request.setAttribute("cbsDelinerPage", entity);
            Integer slaType = null;
            if (entity.getWlSLA() != null && entity.getWlSLA() != "") {
                if (entity.getWlSLA().equals("SL1")) {
                    slaType = 1;
                } else if (entity.getWlSLA().equals("SL2")) {
                    slaType = 2;
                } else if (entity.getWlSLA().equals("SL3")) {
                    slaType = 3;
                } else if (entity.getWlSLA().equals("SL4")) {
                    slaType = 4;
                } else if (entity.getWlSLA() == null) {
                    slaType = 10;
                } else if (entity.getWlSLA().equals("无")) {
                    slaType = 10;
                }
                request.setAttribute("slaType", slaType);
            } else {
                request.setAttribute("slaType", 10);
            }
            List<TSType> sendReasonList = systemService.findHql("FROM TSType where TSTypegroup.typegroupcode='send_reason'");
            request.setAttribute("sendReasonList", sendReasonList);
            List<TSType> signTypeList = systemService.findHql("FROM TSType where TSTypegroup.typegroupcode='signType'");
            request.setAttribute("signTypeList", signTypeList);
            if (entity.getSignFile() != null && entity.getSignFile() != "") {
                ZyFileLogEntity zyFileLogEntity = systemService.singleResult("from ZyFileLogEntity where id = '" + entity.getSignFile() + "'");
                request.setAttribute("zyFileLogEntity", zyFileLogEntity);
            }
            //获取发货单状态
            TSType deliverStatus = systemService.singleResult("from TSType where typecode='" + entity.getStatus() + "'and TSTypegroup.typegroupcode='deliver_status'");
            request.setAttribute("deliverStatus", deliverStatus);
            List<TSType> tsTypes = systemService.findHql("FROM TSType where TSTypegroup.typegroupcode='kuwei'");
            request.setAttribute("types", tsTypes);
            //获取所有的发货单类型
            String hqlType = "from TSType where TSTypegroup.typegroupcode='Deliver_Type'";
            List<TSType> deliverTypeList = systemService.findHql(hqlType);
            request.setAttribute("deliverTypeList", deliverTypeList);
            //获取备件申请人信息
            if (entity != null) {
                String hql = "from CbsServiceEntity where code='" + entity.getCrCode() + "'";
                CbsServiceEntity cbsServiceEntity = systemService.singleResult(hql);

                request.setAttribute("cbsServiceEntity", cbsServiceEntity);
                List<Map<String, Object>> list = new ArrayList();
                Map map = new HashMap();
                if (entity.getIsHb() != null && entity.getIsHb().equals("1")) {
                    if (entity.getSpaceNumber() != null && entity.getSpaceNumber() != "") {
                        String[] split = entity.getSpaceNumber().split("/");
                        for (int i = 0; i < split.length; i++) {
                            CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.singleResult("from CbsEquipmentApplyEntity where recordId = '" + split[i] + "'");
                            if (cbsEquipmentApplyEntity != null) {
                                map.put("name", cbsEquipmentApplyEntity.getCreateName());
                                //申请人电话
                                List<String> mobilePhone = systemService.findListbySql("select mobilePhone from t_s_user where id=(select id from t_s_base_user where username='" + cbsEquipmentApplyEntity.getCreateBy() + "')");
                                if (mobilePhone != null && mobilePhone.size() > 0) {
                                    map.put("phone", mobilePhone);
                                }
                                //获取服务商信息
                                List<String> shortname = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + cbsEquipmentApplyEntity.getServiceId() + "'");
                                if (shortname.size() != 0) {
                                    map.put("shortname", shortname.get(0));
                                }
                                list.add(map);
                            }
                        }
                    }

                    if (list != null && list.size() > 0) {
                        request.setAttribute("list", list);
                    } else {
                        request.setAttribute("list", null);
                    }
                    request.setAttribute("Hb", "1");
                } else {
                    if (entity.getEquipmentApplyId() != null) {
                        CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.getEntity(CbsEquipmentApplyEntity.class, entity.getEquipmentApplyId().getId());
                        request.setAttribute("cbsEquipmentApplyEntity", cbsEquipmentApplyEntity);
                        //申请人电话
                        List<String> mobilePhone = systemService.findListbySql("select mobilePhone from t_s_user where id=(select id from t_s_base_user where username='" + cbsEquipmentApplyEntity.getCreateBy() + "')");
                        if (mobilePhone != null && mobilePhone.size() > 0) {
                            request.setAttribute("mobilePhone", mobilePhone);
                        }
                        //获取服务商信息
                        List<String> shortname = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + cbsEquipmentApplyEntity.getServiceId() + "'");
                        if (shortname.size() != 0) {
                            request.setAttribute("shortname", shortname.get(0));
                        }
                    }
                    request.setAttribute("Hb", "2");
                }
                //获取该服务单类型是否是引擎翻新
                if (cbsServiceEntity != null && cbsServiceEntity.getServiceType2() != null) {
                    if (cbsServiceEntity.getServiceType2().getName().equals("引擎翻新")) {
                        request.setAttribute("yqfx", 1);
                    }
                }

                if (cbsServiceEntity != null) {
                    String hql1 = "select * FROM cbs_service_assign_list WHERE service_id='" + cbsServiceEntity.getId() + "' AND assign_torole in(2,3) AND status NOT in(2,4) ORDER BY create_date DESC LIMIT 1";
                    Map<String, Object> assignMap = systemService.findOneForJdbc(hql1);
                    if (assignMap != null) {
                        String engineerId = (String) assignMap.get("assign_touser");
                        ZyEngineerEntity engineer = systemService.get(ZyEngineerEntity.class, engineerId);
                        request.setAttribute("engineer", engineer);
                    }
                }
            }

        }
        //获取发货sla
        TSType fhSLA = systemService.singleResult("from TSType where typecode='" + entity.getFhSLA() + "' and TSTypegroup.typegroupcode='fhSLA'");
        request.setAttribute("fhSLA", fhSLA);
        //根据发货单号获取申请的备件
        List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + entity.getId() + "'");
        request.setAttribute("deliverEquipmentList", deliverEquipmentList);
        List<ZyEsItemEntity> zyEsItemEntitys = systemService.findHql("from ZyEsItemEntity");
        request.setAttribute("zyEsItemEntitys", zyEsItemEntitys);
        List<TSType> types = systemService.findHql("from TSType where TSTypegroup.typegroupcode='kuwei'");
        request.setAttribute("types", types);
        List<ZyFileLogEntity> zyFileLogEntityList = systemService.findHql("from ZyFileLogEntity where businessKey = '" + entity.getId() + "' and businessType = 'S'");
        if (zyFileLogEntityList != null && zyFileLogEntityList.size() > 0) {
            request.setAttribute("zyFileLogEntityList", zyFileLogEntityList);
        } else {
            request.setAttribute("zyFileLogEntityList", null);
        }
        List<ZyFileLogEntity> zyFileLogEntityListSend = systemService.findHql("from ZyFileLogEntity where businessKey = '" + entity.getId() + "' and businessType = 'L'");
        if (zyFileLogEntityListSend != null && zyFileLogEntityListSend.size() > 0) {
            request.setAttribute("zyFileLogEntityListSend", zyFileLogEntityListSend);
        } else {
            request.setAttribute("zyFileLogEntityListSend", null);
        }
        //查询分派到物流以后的发货单操作日志
        List<CbsHandleLogEntity> logisticsLogList = systemService.findHql("from CbsHandleLogEntity where logType=2 and businessId='" + entity.getId() + "' and processStatus=2  ORDER BY createDate DESC");
        request.setAttribute("logisticsLogList", logisticsLogList);
        return new ModelAndView("com/zybk/cbs_deliver/cbsDeliver-sign_details");
    }

    /**
     * 跳转修改到货时间界面
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "goChangeTime")
    public ModelAndView goChangeTime(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbs_deliver/changeTime");
    }

    /**
     * 修改预计到货时间
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "changeTime")
    @ResponseBody
    public AjaxJson changeTime(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        TSUser user = ResourceUtil.getSessionUserName();
        try {

            String id = request.getParameter("id");
            CbsDelinerEntity cbsDelinerEntity = systemService.getEntity(CbsDelinerEntity.class, id);
            String remarks = request.getParameter("remarks");
            String time = request.getParameter("time");
            String phone = request.getParameter("cellPhone");
            String etaQunqualified = request.getParameter("etaQunqualified");
            String etaNotQualifiedMemo = request.getParameter("etaNotQualifiedMemo");

            int i = systemService.updateBySqlString("update cbs_deliver set expectTime = '" + time + "',change_time_reason = '" + remarks + "',eta_standard = " + StaticValue.wdbETA + ",eta_qunqualified = NULL,eta_not_qualified_memo=NULL where id = '" + id + "'");
            if (StringUtil.isNotEmpty(etaQunqualified)) {
                systemService.updateBySqlString("update cbs_deliver set eta_standard = " + StaticValue.dbETA + ",eta_qunqualified='" + etaQunqualified + "',eta_not_qualified_memo='" + etaNotQualifiedMemo + "' where id = '" + id + "'");
            }
            //记录发货单操作日志
            cbsDelinerService.addDeliverLog(user.getRealName() + "修改了预计到货时间。由" + cbsDelinerEntity.getExpectTime() + "修改为" + time + "。", cbsDelinerEntity.getId(), 2);
            map.put("sta", 1);
            ajaxJson.setAttributes(map);
            //TODO 短信 app 通知服务单当前工程师
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(cbsDelinerEntity.getExpectTime());
            Map<String, Object> paraMap = new HashMap<String, Object>();
            paraMap.put("crCode", cbsDelinerEntity.getCrCode());
            paraMap.put("expectTime", format);
            paraMap.put("time", time);
            paraMap.put("code", cbsDelinerEntity.getCode());
            if (phone != null && !phone.equals("")) {
                SendMessage.sendSMSFTL(phone, "message_send_changeTime.ftl", paraMap, systemService);
            }

        } catch (Exception e) {
            map.put("sta", 0);
            ajaxJson.setAttributes(map);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * 计算出未达标时点击保存
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "save")
    public AjaxJson save(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map<String, Object> map = new HashMap<>();
        try {
            String id = request.getParameter("id");
            String notQualified = request.getParameter("notQualified");
            String notQualifiedMemo = request.getParameter("notQualifiedMemo");
            int i = systemService.updateBySqlString("update cbs_deliver set is_standard = '2',not_qualified='" + notQualified + "',not_qualified_memo='" + notQualifiedMemo + "' where id = '" + id + "'");
            if (i > 0) {
                map.put("sta", 1);
            }
        } catch (Exception e) {
            map.put("sta", 0);
            e.getMessage();
        }
        ajaxJson.setAttributes(map);
        return ajaxJson;
    }

    /**
     * 签收
     */
    @ResponseBody
    @RequestMapping(params = "Sign")
    public AjaxJson Sign(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map<String, Object> map = new HashMap<>();
        try {
            String id = request.getParameter("id");
            CbsDelinerEntity cbsDeliner = systemService.get(CbsDelinerEntity.class, id);
            String singMenthod = request.getParameter("singMenthod");
            String signTime = request.getParameter("signTime");
            String fileName = request.getParameter("fileName");
            String signMemo = request.getParameter("signMemo");
            String csaSendTime = request.getParameter("CSASendTime");
            String slaType = request.getParameter("slaType");
            //计算物流时长
            DecimalFormat df = new DecimalFormat("0.00");
            df.setRoundingMode(RoundingMode.HALF_UP);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date qsTime = sdf.parse(signTime);
            Date sendTime = cbsDeliner.getLogisticsSendTime();
            double qsDate = qsTime.getTime();
            double sendDate = sendTime.getTime();
            double wlTime = Double.valueOf(df.format((qsDate - sendDate) / 1000 / 60 / 60));
            String notQualified = request.getParameter("notQualified");
            String notQualifiedMemo = request.getParameter("notQualifiedMemo");
            int i = systemService.updateBySqlString("update cbs_deliver set sign_standard = " + StaticValue.wdbSign + ",sign_memo='" + signMemo + "',sign_method='" + singMenthod + "',gettime='" + signTime + "',logistics_duration='" + wlTime + "',status='7' where id = '" + id + "'");
            if (notQualified != "" && notQualified != null) {
                int i1 = systemService.updateBySqlString("update cbs_deliver set sign_standard = " + StaticValue.dbSign + ",not_qualified='" + notQualified + "',not_qualified_memo='" + notQualifiedMemo + "' where id = '" + id + "'");
            }
            if (fileName == "") {
                systemService.updateBySqlString("update cbs_deliver set sign_file = NULL where id = '" + id + "'");
            }
            if (fileName != "") {
                systemService.updateBySqlString("update cbs_deliver set sign_file = '" + fileName + "' where id = '" + id + "'");
            }
            if ("1".equals(cbsDeliner.getFhSLA())) {
                Map<String, Object> map1 = cbsDelinerService.ifQualifiedLevel(csaSendTime, signTime, "pt");
                Integer status = (Integer) map1.get("status");
                if (status > Integer.valueOf(slaType)) {
                    systemService.updateBySqlString("update cbs_deliver set is_standard = " + StaticValue.db + " where id = '" + id + "'");
                } else {
                    systemService.updateBySqlString("update cbs_deliver set is_standard = " + StaticValue.wdb + " where id = '" + id + "'");
                }
            }
            if ("2".equals(cbsDeliner.getFhSLA())) {
                Map<String, Object> map1 = cbsDelinerService.ifQualifiedLevel(csaSendTime, signTime, null);
                Integer status = (Integer) map1.get("status");
                if (status > Integer.valueOf(slaType)) {
                    systemService.updateBySqlString("update cbs_deliver set is_standard = " + StaticValue.db + " where id = '" + id + "'");
                } else {
                    systemService.updateBySqlString("update cbs_deliver set is_standard = " + StaticValue.wdb + " where id = '" + id + "'");
                }
            }
            if ("3".equals(cbsDeliner.getFhSLA())) {
                SimpleDateFormat signT = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdfCsa = new SimpleDateFormat("yyyy-MM-dd");
                Date parse = signT.parse(signTime);
                Date parseCsa = sdfCsa.parse(csaSendTime);
                if (parse.getTime() > parseCsa.getTime()) {
                    systemService.updateBySqlString("update cbs_deliver set is_standard = " + StaticValue.db + " where id = '" + id + "'");
                } else {
                    systemService.updateBySqlString("update cbs_deliver set is_standard = " + StaticValue.wdb + " where id = '" + id + "'");
                }
            }

            String equipment = request.getParameter("equipment");
            JSONArray json = JSONArray.fromObject(equipment);
            System.out.println("json:" + json);
            JSONObject jsonOne;
            for (int j = 0; j < json.size(); j++) {
                jsonOne = json.getJSONObject(j);
                String equipmentId = jsonOne.getString("deliverEquipmentId");
                String wlCode = jsonOne.getString("wlNumber");
                if (StringUtil.isNotEmpty(equipmentId)) {
                    CbsDeliverEquipmentEntity de = systemService.get(CbsDeliverEquipmentEntity.class, equipmentId);
                    de.setLogisticsNumber(wlCode);
                    // Add start 20190116 签收时修改序列号 Amy
                    de.setDeliverSn(jsonOne.getString("sns"));
                    de.setDeliverErcode(jsonOne.getString("qrcodes"));
                    // Add End 20190116 签收时修改序列号 Amy
                    systemService.saveOrUpdate(de);
                }
            }
            if (i > 0) {
                map.put("st", 1);
                //记录操作日志
                //获取登录的用户信息
                TSUser user = ResourceUtil.getSessionUserName();
                cbsDelinerService.addDeliverLog(user.getRealName() + "已签收", cbsDeliner.getId(), 2);
                //Add start Amy 181113 增加向收货人发送微信消息
                List<Map<String, String>> list = new ArrayList<>();
                List<CbsDelinerEntity> CbsDelinerEntityList = systemService.findHql("from CbsDelinerEntity where  id = '" + id + "'");
                if (CbsDelinerEntityList.size() > 0) {
                    String content = "尊敬的客户：您的服务单<" + CbsDelinerEntityList.get(0).getCrCode() + ">所申请的备件已于<" + signTime + ">签收。请您妥善保管备件，感谢您的配合。【中影巴可客服部】";
                    if (StringUtil.isNotEmpty(CbsDelinerEntityList.get(0).getPhone().trim())) {
                        List<TSUser> user1 = systemService.findByProperty(TSUser.class, "mobilePhone", CbsDelinerEntityList.get(0).getPhone().trim());
                        if (user1 != null && user1.size() > 0) {
                            if (StringUtil.isNotEmpty(user1.get(0).getOpenId())) {
                                Map<String, String> mapwx = new HashMap<>();
                                mapwx.put("openid", user1.get(0).getOpenId());
                                mapwx.put("message", content);
                                list.add(mapwx);
                                wxCommonService.sendMsgForWx(list);
                            }
                        }
                    }
                }

                //Add end Amy 181113 
            } else if (i == 0) {
                map.put("st", 2);
            }
            if (cbsDeliner.getFhSLA() != null) {

            }


        } catch (Exception e) {
            map.put("st", 0);
            e.getMessage();
        }

        ajaxJson.setAttributes(map);
        return ajaxJson;

    }

    /**
     * 比较预计到货时间是否和csa派单时间是同一天
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "compareTimeForDay")
    public AjaxJson compareTimeForDay(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            String time = request.getParameter("time");
            String csaSendTime = request.getParameter("CSASendTime");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfCsa = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = sdf.parse(time);
            Date parseCsa = sdfCsa.parse(csaSendTime);
            if (parse.getTime() == parseCsa.getTime()) {
                ajaxJson.setSuccess(true);
            } else {
                ajaxJson.setSuccess(false);
            }
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * 计算服务等级是否达标
     */
    @ResponseBody
    @RequestMapping(params = "ifQualified")
    public AjaxJson ifQualified(HttpServletRequest request) throws ParseException {
        AjaxJson ajaxJson = new AjaxJson();
        String type = request.getParameter("type");
        Map<String, Object> map = new HashMap();
        if ("send".equals(type)) {
            String newTime = request.getParameter("time");
            String oldTime = request.getParameter("CSASendTime");
            String sla = request.getParameter("sla");
            map = cbsDelinerService.ifQualifiedLevel(oldTime, newTime, sla);
        }
        if ("sendJi".equals(type)) {
            String newTime = request.getParameter("time");
            String oldTime = request.getParameter("CSASendTime");
            map = cbsDelinerService.ifQualifiedLevel(oldTime, newTime, null);
        }
        ajaxJson.setAttributes(map);
        return ajaxJson;
    }

    /**
     * 发货
     */
    @ResponseBody
    @RequestMapping(params = "sendHuo")
    public AjaxJson sendHuo(CbsDelinerEntity cbsDelinerEntity, HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        try {
            ajaxJson = cbsDelinerService.sendHuo(cbsDelinerEntity, request);
            map.put("sta", 1);
        } catch (Exception e) {
            map.put("sta", 0);
            e.getMessage();
        }
        ajaxJson.setAttributes(map);
        return ajaxJson;
    }

    public CbsReturnEquipmentEntity getcbsReturnEquipmentEntiy() {
        CbsReturnEquipmentEntity cbsReturnEquipmentEntity = new CbsReturnEquipmentEntity();
        return cbsReturnEquipmentEntity;

    }

    public CbsReturnEquipmentDetailEntity getCbsReturnEquipmentDetailEntity() {
        CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity = new CbsReturnEquipmentDetailEntity();
        return cbsReturnEquipmentDetailEntity;
    }

    /**
     * 合并发货
     */
    @ResponseBody
    @RequestMapping(params = "send")
    public AjaxJson send(CbsDelinerEntity cbsDelinerEntity, HttpServletRequest request) throws Exception {
        TSUser user = ResourceUtil.getSessionUserName();
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        StringBuffer stringBuffer = new StringBuffer(); //备件申请单号合并显示
        StringBuffer sb = new StringBuffer();  //原发货单code
        try {

            TSTerritory tsTerritory = new TSTerritory();
            TSTerritory tsTerritory2 = new TSTerritory();
            String trim = cbsDelinerEntity.getShi().getId().trim();
            String trim1 = cbsDelinerEntity.getSheng().getId().trim();
            tsTerritory.setId(trim1);
            tsTerritory2.setId(trim);
            //备件
            String equipmentIds = request.getParameter("EquipmentIds");
            //发货单
            String ids = request.getParameter("ids");

            if (ids.contains(",")) {
                for (String id : ids.split(",")) {
                    CbsDelinerEntity cbsDelinerEntity1 = systemService.getEntity(CbsDelinerEntity.class, id);
                    if (StringUtil.isNotEmpty(cbsDelinerEntity1)) {
                        sb.append(cbsDelinerEntity1.getCode());
                        sb.append(",");
                    }
                    if (cbsDelinerEntity1.getEquipmentApplyId() != null && cbsDelinerEntity1.getEquipmentApplyId().getId() != null) {
                        stringBuffer.append(cbsDelinerEntity1.getSpaceNumber());  //备件申请单号
                        stringBuffer.append("/");

                    }

                }
            } else {
                CbsDelinerEntity cbsDelinerEntity1 = systemService.getEntity(CbsDelinerEntity.class, ids);
                if (cbsDelinerEntity1.getEquipmentApplyId() != null && cbsDelinerEntity.getEquipmentApplyId().getCode() != null) {
                    stringBuffer.append(cbsDelinerEntity.getEquipmentApplyId().getCode());  /*备件申请单code*/
                    stringBuffer.append("/");
                }
            }

            String deliverCode = cbsDelinerService.getDelinerCode(); //发货单号
            cbsDelinerEntity.setCode(deliverCode);
            cbsDelinerEntity.setSheng(tsTerritory);
            cbsDelinerEntity.setShi(tsTerritory2);
            cbsDelinerEntity.setStatus(StaticValue.wldfh);
            cbsDelinerEntity.setIsHb("1");
            cbsDelinerEntity.setCSASendTime(new Date());
            cbsDelinerEntity.setFhCSA(user);
            cbsDelinerEntity.setDeliverLogistics(cbsDelinerEntity.getDeliverLogistics());
            if (stringBuffer.toString() != null && !stringBuffer.toString().equals("")) {
                String substring = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
                cbsDelinerEntity.setSpaceNumber(substring);
            }
            cbsDelinerEntity.setEquipmentApplyId(null);
            cbsDelinerService.saveOrUpdate(cbsDelinerEntity);

            //记录合并发货日志
            CbsHandleLogEntity cbsHandleLogEntity1 = new CbsHandleLogEntity();
            cbsHandleLogEntity1.setBusinessId(cbsDelinerEntity.getId()); //新发货单日志
            cbsHandleLogEntity1.setLogType(2);
            cbsHandleLogEntity1.setCreateName(user.getRealName());
            cbsHandleLogEntity1.setCreateBy(user.getUserName());
            if (sb.toString() != null && !sb.toString().equals("")) {  //原发货单code
                String substring1 = sb.toString().substring(0, sb.toString().length() - 1);
                cbsHandleLogEntity1.setDescription("" + substring1 + "变为已取消,原因为CSA合并发货，生成" + cbsDelinerEntity.getCode() + "");
            }
            systemService.saveOrUpdate(cbsHandleLogEntity1);

            if (ids.contains(",")) {
                for (String id : ids.split(",")) {
                    CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                    cbsHandleLogEntity.setBusinessId(id);  //原发货单日志
                    cbsHandleLogEntity.setLogType(2);
                    cbsHandleLogEntity.setDescription("已取消发货,原因为CSA合并发货");
                    cbsHandleLogEntity.setCreateName(user.getRealName());
                    cbsHandleLogEntity.setCreateBy(user.getUserName());
                    systemService.saveOrUpdate(cbsHandleLogEntity);
                }
            }

            if (equipmentIds != null && equipmentIds != "") {
                for (String id : equipmentIds.split(",")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    //修改发货单ID前的发货备件信息
                    CbsDeliverEquipmentEntity deliverEquipmentEntity = systemService.getEntity(CbsDeliverEquipmentEntity.class, id.trim());
                    CbsDeliverEquipmentEntity deliverEquipment = new CbsDeliverEquipmentEntity();
                    MyBeanUtils.copyBean2Bean(deliverEquipment, deliverEquipmentEntity);
                    deliverEquipment.setId(uuid);
                    systemService.save(deliverEquipment);
                    int i = systemService.updateBySqlString("update cbs_deliver_equipment set  deliver_id ='" + cbsDelinerEntity.getId() + "' where id = '" + id.trim() + "'");
                    // 修改发货单ID前的发货备件信息
                    CbsDeliverEquipmentEntity cbsDeliverEquipmentEntity = systemService.getEntity(CbsDeliverEquipmentEntity.class, id.trim());
                    CbsDeliverEquipmentMapEntity cbsDeliverEquipmentMapEntity = new CbsDeliverEquipmentMapEntity();
                    CbsDelinerEntity cbsDelinerEntity1 = new CbsDelinerEntity();
                    CbsEquipmentApplyEntity cbsEquipmentApplyEntity = new CbsEquipmentApplyEntity();
                    cbsDelinerEntity1.setId(cbsDeliverEquipmentEntity.getDeliverId().getId());
                    if (cbsDeliverEquipmentEntity.getDeliverId().getEquipmentApplyId() != null) {
                        cbsEquipmentApplyEntity.setId(cbsDeliverEquipmentEntity.getDeliverId().getEquipmentApplyId().getId());
                        cbsDeliverEquipmentMapEntity.setEquipmentApplyId(cbsEquipmentApplyEntity);
                    }
                    cbsDeliverEquipmentMapEntity.setDeliverId(cbsDelinerEntity1);
                    cbsDeliverEquipmentMapServiceI.save(cbsDeliverEquipmentMapEntity);
                }
            }
            //创建返件
            List<CbsDeliverEquipmentEntity> cbsDeliverEquipmentEntityList = systemService.findHql("from CbsDeliverEquipmentEntity where  deliverId.id = '" + cbsDelinerEntity.getId() + "'");
            int j = 0;
            if (cbsDeliverEquipmentEntityList != null && cbsDeliverEquipmentEntityList.size() > 0) {
                for (int m = 0; m < cbsDeliverEquipmentEntityList.size(); m++) {
                    CbsDeliverEquipmentEntity cbsDeliverEquipmentEntity = cbsDeliverEquipmentEntityList.get(m);
                    if (cbsDeliverEquipmentEntity.getIsReturn() != null && cbsDeliverEquipmentEntity.getIsReturn() == 2) {
                        CbsReturnEquipmentEntity cbsReturnEquipmentEntity = getcbsReturnEquipmentEntiy();
                        CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity1 = getCbsReturnEquipmentDetailEntity();

                        /*生成返件单号*/
                        Date date1 = new Date();
                        DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
                        String time1 = format1.format(date1);
                        StringBuffer buffer1 = new StringBuffer();
                        buffer1.append("FJ");
                        buffer1.append(time1);
                        List<Object[]> objects1 = systemService.findListbySql("select * from cbs_return_equipment where to_days(create_date) = to_days(now()) ORDER BY `code` desc;");
                        if (objects1.size() == 0) {
                            buffer1.append("001");
                        } else {
                            String o = (String) objects1.get(0)[1];
                            String s = o.substring(10, 13);
                            int i = Integer.parseInt(s);
                            i++;
                            if (i <= 9) {
                                buffer1.append("00" + i);
                            } else if (i >= 10 && i < 100) {
                                buffer1.append("0" + i);
                            } else {
                                buffer1.append(i);
                            }
                        }

                        //创建返件任务
                        CbsReturnEquipmentEntity returnEquipmentEntity = null;
                        if (j == 0) {
                            //判断返件表中是否存在该数据
                            returnEquipmentEntity = systemService.singleResult("from CbsReturnEquipmentEntity where deliverCode = '" + cbsDelinerEntity.getCode() + "'");
                            if (returnEquipmentEntity == null) {
                                cbsReturnEquipmentEntity.setCode(buffer1.toString());
                                cbsReturnEquipmentEntity.setCinemaName(cbsDelinerEntity.getCinemaName());
                                cbsReturnEquipmentEntity.setSrCode(cbsDelinerEntity.getSrCode());
                                cbsReturnEquipmentEntity.setSoCode(cbsDelinerEntity.getSoCode());
                                cbsReturnEquipmentEntity.setDeliverCode(cbsDelinerEntity.getCode());
                                cbsReturnEquipmentEntity.setCrCode(cbsDelinerEntity.getCrCode());
                                cbsReturnEquipmentEntity.setEquipmentApplyId(cbsDelinerEntity.getEquipmentApplyId());
                                cbsReturnEquipmentEntity.setLogistics(cbsDelinerEntity.getReturnLogistics());
                                cbsReturnEquipmentEntity.setLogisticsCode(cbsDeliverEquipmentEntity.getLogisticsNumber());
                                cbsReturnEquipmentEntity.setStatus(StaticValue.RETURN_STATUS_Log_Type_1);
                                cbsReturnEquipmentServiceI.save(cbsReturnEquipmentEntity);
                                j++;
                            }
                        }

                        if (returnEquipmentEntity == null) {
                            List<Map<String, Object>> forJdbc = systemService.findForJdbc("SELECT\n" +
                                    "*\n" +
                                    "FROM\n" +
                                    "\tcbs_return_equipment_detail\n" +
                                    "WHERE\n" +
                                    "\tdeliver_equuipment_id = '" + equipmentIds.trim() + "'\n" +
                                    "AND return_equipment_id = '" + cbsReturnEquipmentEntity.getId() + "'");
                            if (forJdbc == null || forJdbc.size() == 0) {
                                List<CbsReturnEquipmentEntity> cbsReturnEquipmentEntity1 = systemService.findHql("from CbsReturnEquipmentEntity where deliverCode = '" + cbsDelinerEntity.getCode() + "'");
                                if (cbsReturnEquipmentEntity1.size() > 0) {
                                    cbsReturnEquipmentDetailEntity1.setReturnEquipmentId(cbsReturnEquipmentEntity1.get(0));
                                }
                                cbsReturnEquipmentDetailEntity1.setTypeId(cbsDeliverEquipmentEntity.getTypeId());
                                cbsReturnEquipmentDetailEntity1.setTypeDes(cbsDeliverEquipmentEntity.getTypeDes());
                                cbsReturnEquipmentDetailEntity1.setItemId(cbsDeliverEquipmentEntity.getItemId());
                                cbsReturnEquipmentDetailEntity1.setItem(cbsDeliverEquipmentEntity.getItem());
                                cbsReturnEquipmentDetailEntity1.setItemTotal(cbsDeliverEquipmentEntity.getTotal());
                                cbsReturnEquipmentDetailEntity1.setSn(cbsDeliverEquipmentEntity.getSn());
                                cbsReturnEquipmentDetailEntity1.setDeliverEquipmentId(cbsDeliverEquipmentEntity);
                                cbsReturnEquipmentDetailServiceI.save(cbsReturnEquipmentDetailEntity1);
                            }
                        }
                        //创建返件日志
                        CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                        cbsHandleLogEntity.setBusinessId(cbsReturnEquipmentEntity.getId());
                        cbsHandleLogEntity.setLogType(4);
                        cbsHandleLogEntity.setDescription("创建返件申请单");
                        cbsHandleLogEntity.setCreateName(user.getRealName());
                        cbsHandleLogEntity.setCreateBy(user.getUserName());
                        systemService.saveOrUpdate(cbsHandleLogEntity);

                    }
                }
            }
            //记录操作日志
            //获取登录的用户信息
            cbsDelinerService.addDeliverLog(user.getRealName() + "已发货", cbsDelinerEntity.getId(), 2);


            String emailTitle = "巴可发货通知：<" + cbsDelinerEntity.getCode() + ">-<" + cbsDelinerEntity.getCrCode() + ">-<" + cbsDelinerEntity.getCinemaName() + ">-" + getDateStr(new Date());
            //给仓库联系人发邮件和短信
            cbsDelinerService.sendMail(cbsDelinerEntity, user, "ck", emailTitle, "mail_deliver_CSASend.ftl");
            cbsDelinerService.sendMsg(cbsDelinerEntity, user, "ck", "message_deliver_CSASend.ftl");
            //物流联系人发邮件和短信
            cbsDelinerService.sendMail(cbsDelinerEntity, user, "wl", emailTitle, "mail_deliver_CSASend.ftl");
            cbsDelinerService.sendMsg(cbsDelinerEntity, user, "wl", "message_deliver_CSASend.ftl");

            if (ids.contains(",")) {
                for (String id : ids.split(",")) {
                    systemService.updateBySqlString("update cbs_deliver set status = " + StaticValue.CSAqx + ",is_hb = 1 where id = '" + id + "'");
                    CbsDelinerEntity cbsDelinerEntity1 = systemService.getEntity(CbsDelinerEntity.class, id);
                    if (StringUtil.isNotEmpty(cbsDelinerEntity1)) {
                        List<CbsReturnEquipmentEntity> cbsReturnEquipmentEntityList = systemService.findHql("from CbsReturnEquipmentEntity where deliverCode = '" + cbsDelinerEntity1.getCode() + "'");
                        if (cbsReturnEquipmentEntityList != null && cbsReturnEquipmentEntityList.size() > 0) {
                            for (int i = 0; i < cbsReturnEquipmentEntityList.size(); i++) {
                                systemService.updateBySqlString("update cbs_return_equipment set status = " + StaticValue.RETURN_STATUS_Log_Type_5 + " where id = '" + cbsReturnEquipmentEntityList.get(i).getId() + "'");
                            }
                        }
                    }
                }

            } else {
                systemService.updateBySqlString("update cbs_deliver set status = " + StaticValue.CSAqx + ",is_hb = 1 where id = '" + ids + "'");
                systemService.updateBySqlString("update cbs_return_equipment set status = " + StaticValue.RETURN_STATUS_Log_Type_5 + " where id = '" + ids + "'");
            }
            map.put("sta", 1);
            ajaxJson.setAttributes(map);
            //向备件申请人发送取消发货单通知
            String spaceNumber = cbsDelinerEntity.getSpaceNumber();
            if (StringUtil.isNotEmpty(spaceNumber)) {
                String serviceLivel = "";
                String serviceType = "";
                String serviceCode = "";
                String cinemaName = "";
                String emailT = "";
                if (cbsDelinerEntity.getCrCode() != null) {
                    CbsServiceEntity cbsServiceEntity = systemService.singleResult("from CbsServiceEntity where code = '" + cbsDelinerEntity.getCrCode() + "'");
                    serviceLivel = StringUtil.isNotEmpty(cbsServiceEntity.getLevel()) ? cbsServiceEntity.getLevel() : "";
                    serviceType = StringUtil.isNotEmpty(cbsServiceEntity.getServiceType2().getName()) ? cbsServiceEntity.getServiceType2().getName() : "";
                    serviceCode = StringUtil.isNotEmpty(cbsDelinerEntity.getCrCode()) ? cbsDelinerEntity.getCrCode() : "";
                    cinemaName = StringUtil.isNotEmpty(cbsDelinerEntity.getCinemaName()) ? cbsDelinerEntity.getCinemaName() : "";
                    emailT += "发货单取消：<" + serviceLivel + ">-<" + serviceType + ">-<" + serviceCode + ">-<" + cinemaName + ">-" + getDateStr(new Date());

                }
                Map rsMap = new HashMap();
                TSUser tsUser = ResourceUtil.getSessionUserName();
                rsMap.put("code", serviceCode);
                rsMap.put("qxReason", "CSA合并发货");
                rsMap.put("qxUserName", tsUser.getRealName());
                rsMap.put("qxUserPhone", tsUser.getMobilePhone());
                String[] split = spaceNumber.split("/");
                for (int i = 0; i < split.length; i++) {
                    List<CbsEquipmentApplyEntity> cbsEquipmentApplyEntityList = systemService.findHql("from CbsEquipmentApplyEntity where recordId = '" + split[i] + "'");
                    if (StringUtil.isNotEmpty(cbsEquipmentApplyEntityList) && cbsEquipmentApplyEntityList.size() > 0) {
                        for (int s = 0; s < cbsEquipmentApplyEntityList.size(); s++) {
                            //申请人电话
                            List<String> mobilePhone = systemService.findListbySql("select mobilePhone from t_s_user where id=(select id from t_s_base_user where username='" + cbsEquipmentApplyEntityList.get(s).getCreateBy() + "')");
                            String phone = StringUtil.isNotEmpty(mobilePhone.get(0)) ? mobilePhone.get(0) : "";
                            SendMessage.sendSMSFTL(phone, "sms_deliver_CSAQx.ftl", rsMap, systemService);
                            List<String> email = systemService.findListbySql("select email from t_s_user where id=(select id from t_s_base_user where username='" + cbsEquipmentApplyEntityList.get(s).getCreateBy() + "')");
                            ZyEmailEntity zyEmailEntity = new ZyEmailEntity();
                            zyEmailEntity.setEmailSubject(emailT);
                            zyEmailEntity.setEmailReceiver(StringUtil.isNotEmpty(email.get(0)) ? email.get(0) : "");
                            SendMailUtil.sendFtlMail(zyEmailEntity, "mail_deliver_CSAQx.ftl", rsMap, systemService);
                        }

                    }
                }
            }
        } catch (Exception e) {
            map.put("sta", 0);
            ajaxJson.setAttributes(map);
            e.getMessage();
        }

        return ajaxJson;
    }

    /*CSA发货时间的两个小时后 状态依然是‘物流代发货’，向物流联系人和CSA发送超时提醒。*/
    public void selectStatus(final String id, final TSUser tsUser) throws UnsupportedEncodingException, MalformedURLException {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {

                try {
                    CbsDelinerEntity cbsDelinerEntity = systemService.singleResult("from CbsDelinerEntity where code = '" + id + "'");
                    // CSA发货时间的两个小时后 状态依然是‘物流代发货’，向物流联系人和CSA发送超时提醒
                    if (StringUtil.isNotEmpty(cbsDelinerEntity)) {
                        if (cbsDelinerEntity.getStatus().equals(StaticValue.wldfh)) {
                            StringBuffer stringBuffer = new StringBuffer();
                            Map<String, Object> objectMap = new HashMap<>();
                            stringBuffer.append("物流发货超时提醒：<" + cbsDelinerEntity.getCode() + ">");
                            objectMap.put("code", cbsDelinerEntity.getCode());
                            if (cbsDelinerEntity.getCrCode() != null) {
                                stringBuffer.append("<" + cbsDelinerEntity.getCrCode() + ">--");
                            }
                            if (cbsDelinerEntity.getCinemaName() != null) {
                                stringBuffer.append("<" + cbsDelinerEntity.getCinemaName() + ">-");
                            }
                            SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                            Date date = new Date();
                            String time = sdf.format(date);
                            stringBuffer.append(time);
                            cbsDelinerService.sendMsg(cbsDelinerEntity, tsUser, "wl", "message_send_timeTask_sms.ftl");
                            cbsDelinerService.sendMsg(cbsDelinerEntity, tsUser, "ck", "message_send_timeTask_sms.ftl");
                            cbsDelinerService.sendMsg(cbsDelinerEntity, tsUser, "CSA", "message_send_timeTask_sms.ftl");
                            cbsDelinerService.sendMail(cbsDelinerEntity, tsUser, "wl", stringBuffer.toString(), "message_send_timeTask_email.ftl");
                            cbsDelinerService.sendMail(cbsDelinerEntity, tsUser, "CSA", stringBuffer.toString(), "message_send_timeTask_email.ftl");
                            cbsDelinerService.sendMail(cbsDelinerEntity, tsUser, "ck", stringBuffer.toString(), "message_send_timeTask_email.ftl");

                        }
                    }
                } catch (Exception e) {
                    System.err.println("网络异常,发送短信失败！");
                }


            }
        }, StaticValue.selectStatusTiem);
    }

    /**
     * 删除上传的文件
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "delFile")
    public AjaxJson delFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            String id = oConvertUtils.getString(request.getParameter("id"));
            if (id != null && id != "") {
                systemService.deleteEntityById(ZyFileLogEntity.class, id);
                j.setMsg("文件删除成功");
                j.setSuccess(true);
            }
        } catch (Exception e) {
            j.setMsg(e.getMessage());
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 更新发货单信息
     *
     * @param
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(CbsDelinerEntity cbsDeliner, HttpServletRequest request) throws Exception {
        AjaxJson j = new AjaxJson();
        String id = request.getParameter("deliverid"); /*发货单id*/
        String deliverStatus = request.getParameter("deliverStatus");
        String deliverType = request.getParameter("deliverType");
        String soCode = request.getParameter("soCode");
        String srCode = request.getParameter("srCode");
        String equipment = request.getParameter("equipment");
        String fhSLA = request.getParameter("fhSLA");
        String thProvince = request.getParameter("thProvince");
        TSTerritory thSheng = systemService.get(TSTerritory.class, thProvince);
        String thAddress = request.getParameter("thAddress");
        String thShi = request.getParameter("thShi");
        TSTerritory thCity = systemService.get(TSTerritory.class, thShi);
        String WlSx = request.getParameter("WlSx");
        String kuwei = request.getParameter("kuwei");
        String deliverMemo = request.getParameter("deliverMemo");
        String logisticsMemo = request.getParameter("logisticsMemo");
        String deliverWarehouseId = request.getParameter("deliverWarehouse");
        CbsWarehouseEntity deWarehouse = null;
        if (StringUtil.isNotEmpty(deliverWarehouseId)) {
            deWarehouse = systemService.get(CbsWarehouseEntity.class, deliverWarehouseId);
        }

        //获取登录的用户信息
        TSUser user = ResourceUtil.getSessionUserName();

        cbsDeliner = systemService.get(CbsDelinerEntity.class, id);
        //修改前的so号,sr
        String so = cbsDeliner.getSoCode();
        String sr = cbsDeliner.getSrCode();

        String logistics = request.getParameter("deliverLogistics_id");
        if (logistics.equals("0")) {
            logistics = "";
        }
        cbsDeliner.setDeliverLogistics(logistics);
        cbsDeliner.setReturnLogistics(request.getParameter("returnLogistics"));
        cbsDeliner.setThSheng(thSheng);
        cbsDeliner.setThCity(thCity);
        cbsDeliner.setThAddress(thAddress);
        cbsDeliner.setFhSLA(fhSLA);
        cbsDeliner.setDeliverWarehouseId(deWarehouse);
        cbsDeliner.setwLocaltion(kuwei);
        cbsDeliner.setDeliverDes(deliverMemo);
        cbsDeliner.setLogisticsMemo(logisticsMemo);
        cbsDeliner.setWlSLA(WlSx);
        cbsDeliner.setSrCode(srCode);
        cbsDeliner.setSoCode(soCode);
        //原物流
        String exLogisticsName = "";
    	List<String> exCbsDelinerEntity = systemService.findListbySql("select deliver_logistics from cbs_deliver where id = '" +  id + "'");
   	 if (exCbsDelinerEntity!=null && exCbsDelinerEntity.size() >0) {
   		 exLogisticsName = exCbsDelinerEntity.get(0);
   	 }
        //修改服务单中的sr，so 和备件申请单的sr
   	    if (StringUtil.isNotEmpty(cbsDeliner.getCrCode())) {
   	        CbsServiceEntity ser = systemService.singleResult("from CbsServiceEntity where code='" + cbsDeliner.getCrCode() + "'");
   	        if (StringUtil.isNotEmpty(ser)) {
   	            if (StringUtil.isNotEmpty(soCode) && !soCode.equals(so)) {
   	                ser.setSo(soCode);
   	                //增加服务单日志，发货单修改了so
   	                cbsServiceLogServiceI.addServiceLog(ser, StaticValue.Close_Service_Log_Type_2, "发货单:" + cbsDeliner.getCode() + "修改服务单SO：" + ser.getSo() + "为：" + soCode, null);
   	            }
   	            if (StringUtil.isNotEmpty(srCode) && !srCode.equals(sr)) {
   	                ser.setSr(srCode);
   	                //增加服务单日志，发货单修改了sr
   	                cbsServiceLogServiceI.addServiceLog(ser, StaticValue.Close_Service_Log_Type_2, "发货单:" + cbsDeliner.getCode() + "修改服务单SR：" + ser.getSr() + "为：" + srCode, null);
   	            }

   	            systemService.saveOrUpdate(ser);

   	            //修改备件申请单中的sr
   	            List<CbsEquipmentApplyEntity> appList = systemService.findHql("from CbsEquipmentApplyEntity where serviceId='" + ser.getId() + "'");
   	            if (appList != null && appList.size() > 0) {
   	                for (CbsEquipmentApplyEntity eqApp : appList) {
   	                    eqApp.setSrCode(srCode);
   	                    systemService.saveOrUpdate(eqApp);
   	                }
   	            }
   	        }
   	    }

        //获取发货物流和返件物流联系人
        String deliverLogistics = cbsDeliner.getDeliverLogistics();
        String returnLogistics = cbsDeliner.getReturnLogistics();

        message = "发货单信息更新成功";
        System.out.println("id:" + id);
        try {
            //还没有发货
            if (deliverStatus.equals("CSA待发货") || deliverStatus.equals("物流待发货") || deliverStatus.equals("欠货中")) {
                cbsDeliner.setDeliverType(deliverType);
                cbsDeliner.setDeliverLogistics(request.getParameter("deliverLogistics_id"));
                cbsDeliner.setUpdateDate(new Date());
                systemService.saveOrUpdate(cbsDeliner);

                ZyEquipmentTypeEntity zyEquipmentType = null;  //备件类型
                ZyEsItemEntity zyEsItem = null;
                JSONArray json = JSONArray.fromObject(equipment);
                System.out.println("json:" + json);
                JSONObject jsonOne;
                for (int i = 0; i < json.size(); i++) {
                    jsonOne = json.getJSONObject(i);
                    String deliverEquipmentId = jsonOne.getString("deliverEquipmentId");
                    String itemId = jsonOne.getString("itemId");
                    String item = jsonOne.getString("item");
                    String equipmentTypeId = jsonOne.getString("equipmentType");
                    String sn = jsonOne.getString("sn");
                    String memo = jsonOne.getString("memo");
                    String isReturn = jsonOne.getString("isReturn");
                    String applyLayer = jsonOne.getString("applyLayer");
                    String applyReason = jsonOne.getString("applyReason");

                    /*添加发货备件*/
                    CbsDeliverEquipmentEntity cbsDeliverEquipment = systemService.get(CbsDeliverEquipmentEntity.class, deliverEquipmentId);
                    if (equipmentTypeId != null) { //设置备件类型
                        zyEquipmentType = zyEquipmentTypeService.singleResult("from ZyEquipmentTypeEntity where id='" + equipmentTypeId + "'");
                    }
                    if (itemId != null && !itemId.equals("")) { //设置备件号
                        zyEsItem = systemService.singleResult("from ZyEsItemEntity where id='" + itemId + "'");
                    }
                    if (StringUtil.isNotEmpty(zyEquipmentType)) {
                        cbsDeliverEquipment.setTypeId(zyEquipmentType);
                        cbsDeliverEquipment.setTypeDes(zyEquipmentType.getTypeDesc());
                    } else {
                        cbsDeliverEquipment.setTypeId(null);
                        cbsDeliverEquipment.setTypeDes("");
                    }
                    if (StringUtil.isNotEmpty(item)) {
                        cbsDeliverEquipment.setItem(item.trim());
                        cbsDeliverEquipment.setItemId(null);
                    } else {
                        cbsDeliverEquipment.setItemId(zyEsItem);
                        if (StringUtil.isNotEmpty(zyEsItem)) {
                            cbsDeliverEquipment.setItem(zyEsItem.getItem());
                        }
                    }
//                    cbsDeliverEquipment.setMemo(memo);
                    cbsDeliverEquipment.setIsReturn(Integer.valueOf(isReturn));
                    cbsDeliverEquipment.setApplyLayer(Integer.valueOf(applyLayer));
                    cbsDeliverEquipment.setTotal(1);
                    cbsDeliverEquipment.setSn(sn);
                    cbsDeliverEquipment.setApplyReason(applyReason);
                    cbsDeliverEquipment.setUpdateDate(new Date());
                    cbsDeliverEquipmentService.saveOrUpdate(cbsDeliverEquipment);
                }

            }
            //已发货状态下修改发货单
            if (deliverStatus.equals("CSA待发货") || deliverStatus.equals("物流待发货") || deliverStatus.equals("欠货中") || deliverStatus.equals("已签收") || deliverStatus.equals("物流收待签")) {
                cbsDeliner.setUpdateDate(new Date());
                systemService.saveOrUpdate(cbsDeliner);

                //修改发货单中所有的SO，SR
                if (StringUtil.isNotEmpty(cbsDeliner.getCrCode())) {
                List<CbsDelinerEntity> cbsDeliners = systemService.findHql("from CbsDelinerEntity where crCode='" + cbsDeliner.getCrCode() + "'");
	                if (cbsDeliners.size() > 0) {
	                    for (CbsDelinerEntity deliner : cbsDeliners) {
	                        if (StringUtil.isNotEmpty(soCode) && !soCode.equals(so)) {
	                            deliner.setSoCode(soCode);
	                            cbsDelinerService.addDeliverLog("将发货单SO：" + so + "，改为：" + soCode, deliner.getId(), 1);
	                        }
	                        if (StringUtil.isNotEmpty(srCode) && !srCode.equals(sr)) {  //8月29，添加可修改sr号，9月3号，修改判断页面传值，页面传值不为空时才修改sr
	                            deliner.setSrCode(srCode);
	                            cbsDelinerService.addDeliverLog("将发货单SR：" + sr + "，改为：" + srCode, deliner.getId(), 1);
	                        }
	                        systemService.saveOrUpdate(deliner);
	                    }
	                }
                }

                //修改返件的so，sr
           	    if (StringUtil.isNotEmpty(cbsDeliner.getCrCode())) {
	                List<CbsReturnEquipmentEntity> returnEquipmentList = systemService.findHql("from CbsReturnEquipmentEntity where crCode='" + cbsDeliner.getCrCode() + "'");
	                if (returnEquipmentList != null && returnEquipmentList.size() > 0) {
	                    for (CbsReturnEquipmentEntity returnEquipmentEntity : returnEquipmentList) {
	                        if (StringUtil.isNotEmpty(soCode) && !soCode.equals(so)) {
	                            returnEquipmentEntity.setSoCode(cbsDeliner.getSoCode());
	                            cbsReturnEquipmentServiceI.createReturnLog(returnEquipmentEntity.getId(), "发货单:" + cbsDeliner.getCode() + "修改返件SO,将SO：" + so + ",改为：" + soCode, user);
	                        }
	                        if (StringUtil.isNotEmpty(srCode) && !srCode.equals(sr)) {
	                            returnEquipmentEntity.setSrCode(srCode); //8月29号，增加支持修改sr
	                            cbsReturnEquipmentServiceI.createReturnLog(returnEquipmentEntity.getId(), "发货单:" + cbsDeliner.getCode() + "修改返件SR,将SR：" + sr + ",改为：" + srCode, user);
	                        }
	                        systemService.saveOrUpdate(returnEquipmentEntity);
	                    }
	                }
           	    }
            }

            //记录操作日志
            cbsDelinerService.addDeliverLog(user.getRealName() + "修改了发货单", cbsDeliner.getId(), 1);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);

            if (deliverStatus.equals("物流待发货")){
                //给原物流发取消邮件
                if(!exLogisticsName.isEmpty() && !exLogisticsName.equals(cbsDeliner.getDeliverLogistics())){
                    TSDepart tsDepart = systemService.singleResult("from TSDepart where departname = '" + exLogisticsName + "' and orgType='logistics' ");
                    if (tsDepart != null) {
                    	List<ZyContactsEntity> wlContactsList = systemService.findHql("from ZyContactsEntity where belongOrg.id = '" + tsDepart.getId() + "' and state='" + StaticValue.DIC_ENGINEER_STATE_ONJOB + "'");
                        if (wlContactsList != null && wlContactsList.size() > 0) {
                            for (ZyContactsEntity wlContacts : wlContactsList) {
                                if (wlContacts != null && StringUtil.isNotEmpty(wlContacts.getEmail())) {
                                    Map<String, Object> paraMap1 = new HashMap<>();
                                    paraMap1.put("code", cbsDeliner.getCode());
                                    paraMap1.put("qxUserName", user.getRealName());
                                    paraMap1.put("qxUserPhone",user.getMobilePhone());
                                    paraMap1.put("qxReason", "CSA转派");
                                    String wlEmail = wlContacts.getEmail();
                                    ZyEmailEntity eMail = new ZyEmailEntity();
                                    String emailTitle = "发货单取消：<" + cbsDeliner.getCode()  + ">-<" + cbsDeliner.getCinemaName() + ">-" + getDateStr(new Date());
                                    eMail.setEmailSubject(emailTitle);
                                    eMail.setEmailReceiver(wlEmail);
                                    SendMailUtil.sendFtlMail(eMail, "mail_deliver_CSAQx.ftl", paraMap1, systemService);
                                }
                            }

                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            message = "发货单信息更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 获取仓库联系人
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "getWarehousePerson")
    public AjaxJson getWarousePerson(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            String warehouseId = request.getParameter("warehouse");
            CbsWarehouseEntity cbsWarehouseEntity = systemService.singleResult("from CbsWarehouseEntity where id = '" + warehouseId + "'");
            if (cbsWarehouseEntity != null) {
                request.setAttribute("cbsWarehouseEntity", cbsWarehouseEntity);
            }
            ajaxJson.setObj(cbsWarehouseEntity);
        } catch (Exception e) {
            e.getMessage();
        }
        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "sendCFAll")
    public AjaxJson sendCFAll(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        //获取登录的用户信息
        TSUser user = ResourceUtil.getSessionUserName();
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        String deliverId = request.getParameter("deliverid");
        String deliverLogistics = request.getParameter("deliverLogistics");

        message = "发货成功";
        try {
            if (deliverId != null) {
                systemService.updateBySqlString("update cbs_deliver set status = '5',csa_sendtime='" + time + "',deliver_logistics='" + deliverLogistics + "' where id = '" + deliverId + "'");
            }
            CbsDelinerEntity cbsdeliver1 = systemService.get(CbsDelinerEntity.class, deliverId);
            cbsdeliver1.setFhCSA(user);
            systemService.saveOrUpdate(cbsdeliver1);

            //创建返件
            int count = 0;
            List<CbsDeliverEquipmentEntity> isRetureEqList = new ArrayList<>();
            List<CbsDeliverEquipmentEntity> cdeList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + cbsdeliver1.getId() + "'");
            if (cdeList != null && cdeList.size() > 0) {
                for (CbsDeliverEquipmentEntity deliverequipment : cdeList) {
                    if (deliverequipment != null) {
                        if (deliverequipment.getIsReturn() == 2) {
                            count++;
                            isRetureEqList.add(deliverequipment);
                        } else {
                            //如果已有返件详情的备件选择不返件再次发货，删除已有返件详情
                            List<Map<String, Object>> ids = systemService.findForJdbc("select * from cbs_return_equipment_detail where deliver_equuipment_id ='" + deliverequipment.getId() + "'");
                            if (ids != null && ids.size() > 0) {
                                for (Map<String, Object> map : ids) {
                                    String rdId = (String) map.get("id");
                                    systemService.deleteEntityById(CbsReturnEquipmentDetailEntity.class, rdId);

                                }
                            }


                        }
                    }

                }
            }
            if (count > 0) {
                CbsReturnEquipmentEntity returnEquipment = null;
                //判断该发货单是否已有返件任务
                List<CbsReturnEquipmentEntity> returnEquipmentEntityList = systemService.findHql("from CbsReturnEquipmentEntity where deliverCode='" + cbsdeliver1.getCode() + "'");
                if (returnEquipmentEntityList != null && returnEquipmentEntityList.size() > 0 && returnEquipmentEntityList.get(0) != null) {
                    //已有返件，修改返件信息
                    returnEquipment = returnEquipmentEntityList.get(0);
                    returnEquipment.setLogistics(cbsdeliver1.getReturnLogistics());
                    returnEquipment.setSoCode(cbsdeliver1.getSoCode());
                    returnEquipment.setStatus("1");
                    systemService.saveOrUpdate(returnEquipment);

                    //判断发货的备件是否已有返件
                    if (isRetureEqList.size() > 0) {
                        for (CbsDeliverEquipmentEntity cde : isRetureEqList) {
                            if (cde != null) {
                                List<Map<String, Object>> ids = systemService.findForJdbc("select * from cbs_return_equipment_detail where deliver_equuipment_id ='" + cde.getId() + "'");
                                if (ids != null && ids.size() > 0 && ids.get(0) != null) {
                                    //如果已有对应的返件，更新返件信息
                                    CbsReturnEquipmentDetailEntity returnDetail = systemService.get(CbsReturnEquipmentDetailEntity.class, (String) ids.get(0).get("id"));
                                    returnDetail.setReturnEquipmentId(returnEquipment);
                                    returnDetail.setTypeId(cde.getTypeId());
                                    returnDetail.setTypeDes(cde.getTypeDes());
                                    returnDetail.setItemId(cde.getItemId());
                                    returnDetail.setItem(cde.getItem());
                                    returnDetail.setItemTotal(cde.getTotal());
                                    returnDetail.setSn(cde.getSn());
                                    returnDetail.setDeliverEquipmentId(cde);
                                    cbsReturnEquipmentDetailServiceI.save(returnDetail);
                                } else {
                                    CbsReturnEquipmentDetailEntity returnDetail = new CbsReturnEquipmentDetailEntity();
                                    returnDetail.setReturnEquipmentId(returnEquipment);
                                    returnDetail.setTypeId(cde.getTypeId());
                                    returnDetail.setTypeDes(cde.getTypeDes());
                                    returnDetail.setItemId(cde.getItemId());
                                    returnDetail.setItem(cde.getItem());
                                    returnDetail.setItemTotal(cde.getTotal());
                                    returnDetail.setSn(cde.getSn());
                                    returnDetail.setDeliverEquipmentId(cde);
                                    cbsReturnEquipmentDetailServiceI.save(returnDetail);
                                }
                            }
                        }
                    }

                    //记录操作日志
                    CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                    cbsHandleLogEntity.setBusinessId(returnEquipment.getId());
                    cbsHandleLogEntity.setLogType(4);
                    cbsHandleLogEntity.setDescription("修改返件申请");
                    cbsHandleLogEntity.setCreateName(user.getRealName());
                    cbsHandleLogEntity.setCreateBy(user.getUserName());
                    systemService.saveOrUpdate(cbsHandleLogEntity);


                } else {
                    returnEquipment = new CbsReturnEquipmentEntity();
                    //组装返件单号FH+YYYYMMDD+001(增长)
                    Date date1 = new Date();
                    DateFormat format1 = new SimpleDateFormat("YYYYMMdd");
                    String time1 = format1.format(date1);
                    StringBuffer buffer1 = new StringBuffer();
                    buffer1.append("FJ");
                    buffer1.append(time1);
                    List<Object[]> returnEquipmentList = systemService.findListbySql("select * from cbs_return_equipment where to_days(create_date) = to_days(now()) ORDER BY `code` desc;");
                    if (returnEquipmentList.size() == 0) {
                        buffer1.append("001");
                        String s = buffer1.toString();
                        returnEquipment.setCode(s);
                    } else {
                        String o = (String) returnEquipmentList.get(0)[1];
                        String s = o.substring(10, 13);
                        int l = Integer.parseInt(s);
                        l++;
                        if (l <= 9) {
                            buffer1.append("00" + l);
                        } else if (l >= 10 && l < 100) {
                            buffer1.append("0" + l);
                        } else {
                            buffer1.append("" + l);
                        }
                        String string1 = buffer1.toString();
                        returnEquipment.setCode(string1);
                    }
                    returnEquipment.setSrCode(cbsdeliver1.getSrCode());
                    returnEquipment.setCinemaName(cbsdeliver1.getCinemaName());
                    returnEquipment.setName(cbsdeliver1.getUserName());
                    returnEquipment.setPhone(cbsdeliver1.getPhone());
                    returnEquipment.setAddress(cbsdeliver1.getAddress());
                    returnEquipment.setSoCode(cbsdeliver1.getSoCode());
                    returnEquipment.setDeliverCode(cbsdeliver1.getCode());
                    returnEquipment.setCrCode(cbsdeliver1.getCrCode());
                    returnEquipment.setEquipmentApplyId(cbsdeliver1.getEquipmentApplyId());
                    returnEquipment.setStatus(StaticValue.RETURN_STATUS_Log_Type_1);
                    returnEquipment.setLogistics(cbsdeliver1.getReturnLogistics());
                    returnEquipment.setSheng(cbsdeliver1.getSheng());
                    returnEquipment.setShi(cbsdeliver1.getShi());
                    cbsReturnEquipmentServiceI.save(returnEquipment);
                    if (cdeList.size() > 0) {
                        for (CbsDeliverEquipmentEntity deliverequipment : cdeList) {
                            if (deliverequipment != null) {
                                if (deliverequipment.getIsReturn() == 2) {
                                    CbsReturnEquipmentDetailEntity returnEquipmentDetail = new CbsReturnEquipmentDetailEntity();
                                    returnEquipmentDetail.setReturnEquipmentId(returnEquipment);
                                    returnEquipmentDetail.setTypeId(deliverequipment.getTypeId());
                                    returnEquipmentDetail.setTypeDes(deliverequipment.getTypeDes());
                                    returnEquipmentDetail.setItemId(deliverequipment.getItemId());
                                    returnEquipmentDetail.setItem(deliverequipment.getItem());
                                    returnEquipmentDetail.setItemTotal(deliverequipment.getTotal());
                                    returnEquipmentDetail.setSn(deliverequipment.getSn());
                                    returnEquipmentDetail.setDeliverEquipmentId(deliverequipment);
                                    cbsReturnEquipmentDetailServiceI.save(returnEquipmentDetail);
                                }
                            }

                        }
                    }


                }
            }

            //判断这个发货单对应的返件单中是否有返件，没有则取消返件（状态设为已取消）
            if (cbsdeliver1 != null) {
                checkeCountByDeliver(cbsdeliver1.getCode(), user);
            }


            String emailTitle = "巴可发货通知：<" + cbsdeliver1.getCode() + ">-<" + cbsdeliver1.getCrCode() + ">-<" + cbsdeliver1.getCinemaName() + ">-" + getDateStr(new Date());
            //给物流联系人发送邮件和短息
            cbsDelinerService.sendMail(cbsdeliver1, user, "wl", emailTitle, "mail_deliver_CSASend.ftl");
            cbsDelinerService.sendMsg(cbsdeliver1, user, "wl", "message_deliver_CSASend.ftl");
            //给仓库联系人发送邮件和短息
            cbsDelinerService.sendMail(cbsdeliver1, user, "ck", emailTitle, "mail_deliver_CSASend.ftl");
            cbsDelinerService.sendMsg(cbsdeliver1, user, "ck", "message_deliver_CSASend.ftl");

            cbsDelinerService.addDeliverLog(user.getRealName() + "已发货", cbsdeliver1.getId(), 2);
        } catch (Exception e) {
            message = "发货失败";
            e.getMessage();
        }

        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "sendCF")
    public AjaxJson sendCF(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        message = "发货单信息添加成功";
        TSUser user = ResourceUtil.getSessionUserName();
        String deliverId = request.getParameter("deliverid");
        String deliverLogistics = request.getParameter("deliverLogistics");
        String ids = request.getParameter("ids");
        CbsDelinerEntity cbsdeliver1 = systemService.get(CbsDelinerEntity.class, deliverId);
        try {
            CbsDelinerEntity cbsdeliver = new CbsDelinerEntity();
            // 将旧发货单的数据复制给新的发货单
            BeanUtils.copyProperties(cbsdeliver1, cbsdeliver);
            cbsdeliver.setCreateDate(new Date());
            String uuid = getUuid();
            cbsdeliver.setId(uuid);
            //修改发货单状态
            cbsdeliver.setStatus("5");//物流待发货
            String cbsDelinerCode = cbsDelinerService.getDelinerCode();
            cbsdeliver.setCode(cbsDelinerCode);
            cbsdeliver.setStatus("5");
            cbsdeliver.setCSASendTime(new Date());
            cbsdeliver.setFhCSA(user);
            cbsDelinerService.save(cbsdeliver);
            cbsDelinerService.addDeliverLog("由" + cbsdeliver1.getCode() + "拆分生成", cbsdeliver.getId(), 1);

            int count = 0;
            List<CbsDeliverEquipmentEntity> isRetureEqList = new ArrayList<>();
            CbsReturnEquipmentEntity returnEquipmentEntity = null;
            for (String id : ids.split(",")) {
//                if (s1 != "" && s1 != null) {
                systemService.updateBySqlString("update cbs_deliver_equipment set  deliver_id ='" + cbsdeliver.getId() + "'  where id = '" + id + "'");
                CbsDeliverEquipmentEntity cbsDeliverEquipmentEntity = systemService.singleResult("from CbsDeliverEquipmentEntity where id = '" + id + "'");

                if (cbsDeliverEquipmentEntity != null) {

                    //判断是否需要返件
                    if (cbsDeliverEquipmentEntity.getIsReturn() == 2) {
                        isRetureEqList.add(cbsDeliverEquipmentEntity);
                        count++;
                    } else {
                        //如果已有返件详情的备件选择不返件再次发货，删除已有返件详情
                        List<Map<String, Object>> rdIds = systemService.findForJdbc("select * from cbs_return_equipment_detail where deliver_equuipment_id ='" + cbsDeliverEquipmentEntity.getId() + "'");
                        if (rdIds != null && rdIds.size() > 0) {
                            for (Map<String, Object> rdMap : rdIds) {
                                String rdId = (String) rdMap.get("id");
                                systemService.deleteEntityById(CbsReturnEquipmentDetailEntity.class, rdId);
                            }
                        }
                    }
                }


//                }
            }


            //如果需要返件
            if (count > 0) {
                CbsReturnEquipmentEntity returnEquipment = null;
                //判断该发货单是否已有返件任务
                List<CbsReturnEquipmentEntity> returnEquipmentEntityList = systemService.findHql("from CbsReturnEquipmentEntity where deliverCode='" + cbsdeliver.getCode() + "'");
                if (returnEquipmentEntityList != null && returnEquipmentEntityList.size() > 0 && returnEquipmentEntityList.get(0) != null) {
                    //已有返件，修改返件信息
                    returnEquipment = returnEquipmentEntityList.get(0);
                    returnEquipment.setLogistics(cbsdeliver.getReturnLogistics());
                    returnEquipment.setSoCode(cbsdeliver.getSoCode());
                    systemService.saveOrUpdate(returnEquipment);

                    //判断发货的备件是否已有返件
                    if (isRetureEqList != null && isRetureEqList.size() > 0) {
                        for (CbsDeliverEquipmentEntity cde : isRetureEqList) {
                            if (cde != null) {
                                List<Map<String, Object>> rdIds = systemService.findForJdbc("select * from cbs_return_equipment_detail where deliver_equuipment_id ='" + cde.getId() + "'");
                                if (rdIds != null && rdIds.size() > 0 && rdIds.get(0) != null) {
                                    //如果已有对应的返件，更新返件信息
                                    CbsReturnEquipmentDetailEntity returnDetail = systemService.get(CbsReturnEquipmentDetailEntity.class, (String) rdIds.get(0).get("id"));
                                    returnDetail.setReturnEquipmentId(returnEquipment);
                                    returnDetail.setTypeId(cde.getTypeId());
                                    returnDetail.setTypeDes(cde.getTypeDes());
                                    returnDetail.setItemId(cde.getItemId());
                                    returnDetail.setItem(cde.getItem());
                                    returnDetail.setItemTotal(cde.getTotal());
                                    returnDetail.setSn(cde.getSn());
                                    returnDetail.setDeliverEquipmentId(cde);
                                    cbsReturnEquipmentDetailServiceI.save(returnDetail);
                                } else {
                                    CbsReturnEquipmentDetailEntity returnDetail = new CbsReturnEquipmentDetailEntity();
                                    returnDetail.setReturnEquipmentId(returnEquipment);
                                    returnDetail.setTypeId(cde.getTypeId());
                                    returnDetail.setTypeDes(cde.getTypeDes());
                                    returnDetail.setItemId(cde.getItemId());
                                    returnDetail.setItem(cde.getItem());
                                    returnDetail.setItemTotal(cde.getTotal());
                                    returnDetail.setSn(cde.getSn());
                                    returnDetail.setDeliverEquipmentId(cde);
                                    cbsReturnEquipmentDetailServiceI.save(returnDetail);
                                }
                            }

                        }

                    }

                    //记录操作日志
                    CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                    cbsHandleLogEntity.setBusinessId(returnEquipment.getId());
                    cbsHandleLogEntity.setLogType(4);
                    cbsHandleLogEntity.setDescription("修改返件申请");
                    cbsHandleLogEntity.setCreateName(user.getRealName());
                    cbsHandleLogEntity.setCreateBy(user.getUserName());
                    systemService.saveOrUpdate(cbsHandleLogEntity);

                } else {
                    //如果没有返件，则创建返件
                    returnEquipment = new CbsReturnEquipmentEntity();
                    //组装返件单号FH+YYYYMMDD+001(增长)
                    Date date1 = new Date();
                    DateFormat format1 = new SimpleDateFormat("YYYYMMdd");
                    String time1 = format1.format(date1);
                    StringBuffer buffer1 = new StringBuffer();
                    buffer1.append("FJ");
                    buffer1.append(time1);
                    List<Object[]> returnEquipmentList = systemService.findListbySql("select * from cbs_return_equipment where to_days(create_date) = to_days(now()) ORDER BY `code` desc;");
                    if (returnEquipmentList.size() == 0) {
                        buffer1.append("001");
                        String s = buffer1.toString();
                        returnEquipment.setCode(s);
                    } else {
                        String o = (String) returnEquipmentList.get(0)[1];
                        String s = o.substring(10, 13);
                        int l = Integer.parseInt(s);
                        l++;
                        if (l <= 9) {
                            buffer1.append("00" + l);
                        } else if (l >= 10 && l < 100) {
                            buffer1.append("0" + l);
                        } else {
                            buffer1.append("" + l);
                        }
                        String string1 = buffer1.toString();
                        returnEquipment.setCode(string1);
                    }
                    returnEquipment.setSrCode(cbsdeliver.getSrCode());
                    returnEquipment.setCinemaName(cbsdeliver.getCinemaName());
                    returnEquipment.setName(cbsdeliver.getUserName());
                    returnEquipment.setPhone(cbsdeliver.getPhone());
                    returnEquipment.setAddress(cbsdeliver.getAddress());
                    returnEquipment.setSoCode(cbsdeliver.getSoCode());
                    returnEquipment.setDeliverCode(cbsdeliver.getCode());
                    returnEquipment.setCrCode(cbsdeliver.getCrCode());
                    returnEquipment.setEquipmentApplyId(cbsdeliver.getEquipmentApplyId());
                    returnEquipment.setStatus(StaticValue.RETURN_STATUS_Log_Type_1);
                    returnEquipment.setLogistics(cbsdeliver.getReturnLogistics());
                    returnEquipment.setSheng(cbsdeliver1.getSheng());
                    returnEquipment.setShi(cbsdeliver1.getShi());
                    cbsReturnEquipmentServiceI.save(returnEquipment);

                    //判断发货的备件是否已有返件
                    if (isRetureEqList != null && isRetureEqList.size() > 0) {
                        for (CbsDeliverEquipmentEntity cde : isRetureEqList) {
                            if (cde != null) {
                                List<Map<String, Object>> rdIds = systemService.findForJdbc("select * from cbs_return_equipment_detail where deliver_equuipment_id ='" + cde.getId() + "'");
                                if (rdIds != null && rdIds.size() > 0 && rdIds.get(0) != null) {
                                    //如果已有对应的返件，更新返件信息
                                    CbsReturnEquipmentDetailEntity returnDetail = systemService.get(CbsReturnEquipmentDetailEntity.class, (String) rdIds.get(0).get("id"));
                                    returnDetail.setReturnEquipmentId(returnEquipment);
                                    returnDetail.setTypeId(cde.getTypeId());
                                    returnDetail.setTypeDes(cde.getTypeDes());
                                    returnDetail.setItemId(cde.getItemId());
                                    returnDetail.setItem(cde.getItem());
                                    returnDetail.setItemTotal(cde.getTotal());
                                    returnDetail.setSn(cde.getSn());
                                    returnDetail.setDeliverEquipmentId(cde);
                                    cbsReturnEquipmentDetailServiceI.save(returnDetail);
                                } else {
                                    CbsReturnEquipmentDetailEntity returnDetail = new CbsReturnEquipmentDetailEntity();
                                    returnDetail.setReturnEquipmentId(returnEquipment);
                                    returnDetail.setTypeId(cde.getTypeId());
                                    returnDetail.setTypeDes(cde.getTypeDes());
                                    returnDetail.setItemId(cde.getItemId());
                                    returnDetail.setItem(cde.getItem());
                                    returnDetail.setItemTotal(cde.getTotal());
                                    returnDetail.setSn(cde.getSn());
                                    returnDetail.setDeliverEquipmentId(cde);
                                    cbsReturnEquipmentDetailServiceI.save(returnDetail);
                                }
                            }

                        }

                    }
                }


            }

            //判断原发货单对应的返件单中是否还有返件，没有则取消返件
            if (cbsdeliver1 != null) {
                checkeCountByDeliver(cbsdeliver1.getCode(), user);
            }

            String emailTitle = "巴可发货通知：<" + cbsdeliver.getCode() + ">-<" + cbsdeliver.getCrCode() + ">-<" + cbsdeliver.getCinemaName() + ">-" + getDateStr(new Date());
            //给物流联系人发送邮件和短息
            cbsDelinerService.sendMail(cbsdeliver, user, "wl", emailTitle, "mail_deliver_CSASend.ftl");
            cbsDelinerService.sendMsg(cbsdeliver, user, "wl", "message_deliver_CSASend.ftl");
            //给仓库联系人发送邮件和短息
            cbsDelinerService.sendMail(cbsdeliver, user, "ck", emailTitle, "mail_deliver_CSASend.ftl");
            cbsDelinerService.sendMsg(cbsdeliver, user, "ck", "mail_deliver_CSASend.ftl");

        } catch (Exception e) {
            e.printStackTrace();
            message = "发货失败";
            throw new BusinessException(e.getMessage());
        }
        return ajaxJson;
    }


    @RequestMapping(params = "addQH")
    @ResponseBody
    public AjaxJson addQH(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            j=cbsDelinerService.addQH(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
        return j;
    }


    //备件到货点击发货更改发货单状态
    @RequestMapping(params = "doFH")
    @ResponseBody
    public AjaxJson doFH(HttpServletRequest request) {
        //获取登录的用户信息
        String equipment = request.getParameter("equipment");
        TSUser user = ResourceUtil.getSessionUserName();
        AjaxJson j = new AjaxJson();

        String deliverId = request.getParameter("deliverid");
        CbsDelinerEntity cbsdeliver = systemService.get(CbsDelinerEntity.class, deliverId);

        cbsdeliver.setDeliverLogistics(request.getParameter("deliverLogistics"));
        //修改发货单状态
        cbsdeliver.setStatus("5");//物流待发货

        //设置csa发货时间
        cbsdeliver.setCSASendTime(new Date());
        cbsdeliver.setFhCSA(user);

        message = "发货成功";
        try {
            cbsDelinerService.saveOrUpdate(cbsdeliver);

            ZyEquipmentTypeEntity zyEquipmentType = null;
            JSONArray json = JSONArray.fromObject(equipment);
            System.out.println("json:" + json);
            JSONObject jsonOne;
            for (int i = 0; i < json.size(); i++) {

                jsonOne = json.getJSONObject(i);

                String deliverEquipmentId = jsonOne.getString("deliverEquipmentId");
                String itemId = jsonOne.getString("itemId");
                String equipmentTypeId = jsonOne.getString("equipmentType");
                String total = jsonOne.getString("total");
                String sn = jsonOne.getString("sn");
                String memo = jsonOne.getString("memo");
                String isReturn = jsonOne.getString("isReturn");
                String applyLayer = jsonOne.getString("applyLayer");
                String applyReason = jsonOne.getString("applyReason");
                CbsDeliverEquipmentEntity cbsDeliverEquipment = systemService.get(CbsDeliverEquipmentEntity.class, deliverEquipmentId);
                if (total != null && !total.equals("") && Integer.valueOf(total) > 1) {
                    for (int k = 0; k < Integer.valueOf(total) - 1; k++) {
                        CbsDeliverEquipmentEntity cbsDeliverEquipment1 = new CbsDeliverEquipmentEntity();
                        //设置备件类型
                        if (equipmentTypeId != null) {
                            zyEquipmentType = zyEquipmentTypeService.singleResult("from ZyEquipmentTypeEntity where id='" + equipmentTypeId + "'");
                        }
                        if (zyEquipmentType != null) {
                            cbsDeliverEquipment1.setTypeId(zyEquipmentType);
                            cbsDeliverEquipment1.setTypeDes(zyEquipmentType.getTypeDesc());
                        }

                        //设置备件号
                        if (itemId != null) {
                            ZyEsItemEntity zyEsItem = systemService.singleResult("from ZyEsItemEntity where id='" + itemId + "'");
                            System.out.println("zyEsItem:" + zyEsItem);
                            if (zyEsItem != null) {
                                cbsDeliverEquipment1.setItem(zyEsItem.getItem());
                                cbsDeliverEquipment1.setItemId(zyEsItem);
                            }
                        }

                        cbsDeliverEquipment1.setMemo(memo);

                        cbsDeliverEquipment1.setDeliverId(cbsdeliver);
                        cbsDeliverEquipment1.setIsReturn(Integer.valueOf(isReturn));
                        cbsDeliverEquipment1.setApplyLayer(Integer.valueOf(applyLayer));
                        cbsDeliverEquipment1.setTotal(1);
                        cbsDeliverEquipment1.setSn(sn);
                        cbsDeliverEquipment1.setApplyReason(applyReason);
                        cbsDeliverEquipment1.setUpdateDate(new Date());
                        cbsDeliverEquipmentService.save(cbsDeliverEquipment1);
                        //如果备件需要返件，创建返件任务
                        if (cbsDeliverEquipment1.getIsReturn() == 2) {
                            //组装返件单号FH+YYYYMMDD+001(增长)
                            Date date = new Date();
                            DateFormat format = new SimpleDateFormat("YYYYMMdd");
                            String time = format.format(date);
                            System.out.println(time);
                            StringBuffer buffer = new StringBuffer();
                            buffer.append("FJ");
                            buffer.append(time);
                            List<Object[]> returnEquipmentList = systemService.findListbySql("select * from cbs_return_equipment where to_days(create_date) = to_days(now()) ORDER BY `code` desc;");
                            CbsReturnEquipmentEntity returnEquipment = new CbsReturnEquipmentEntity();
                            CbsReturnEquipmentDetailEntity returnEquipmentDetail = new CbsReturnEquipmentDetailEntity();
                            returnEquipment.setSrCode(cbsdeliver.getSrCode());
                            returnEquipment.setSoCode(cbsdeliver.getSoCode());
                            returnEquipment.setDeliverCode(cbsdeliver.getCode());
                            returnEquipment.setCrCode(cbsdeliver.getCrCode());
                            returnEquipment.setEquipmentApplyId(cbsdeliver.getEquipmentApplyId());
                            returnEquipment.setStatus(StaticValue.RETURN_STATUS_Log_Type_1);
                            returnEquipment.setLogistics(cbsdeliver.getReturnLogistics());
                            returnEquipment.setLogisticsCode(cbsDeliverEquipment1.getLogisticsNumber());
                            cbsReturnEquipmentServiceI.save(returnEquipment);

                            if (returnEquipmentList.size() == 0) {
                                buffer.append("001");
                                String s = buffer.toString();
                                returnEquipment.setCode(s);
                                cbsReturnEquipmentServiceI.save(returnEquipment);
                            } else {
                                String o = (String) returnEquipmentList.get(0)[1];
                                String s = o.substring(10, 13);
                                int l = Integer.parseInt(s);
                                l++;
                                if (l <= 9) {
                                    buffer.append("00" + l);
                                } else if (l >= 10 && l < 100) {
                                    buffer.append("0" + l);
                                } else {
                                    buffer.append("" + l);
                                }
                                String string = buffer.toString();
                                returnEquipment.setCode(string);
                                cbsReturnEquipmentServiceI.save(returnEquipment);
                            }
                            returnEquipmentDetail.setReturnEquipmentId(returnEquipment);
                            returnEquipmentDetail.setTypeId(cbsDeliverEquipment1.getTypeId());
                            returnEquipmentDetail.setTypeDes(cbsDeliverEquipment1.getTypeDes());
                            returnEquipmentDetail.setItemId(cbsDeliverEquipment1.getItemId());
                            returnEquipmentDetail.setItem(cbsDeliverEquipment1.getItem());
                            returnEquipmentDetail.setItemTotal(cbsDeliverEquipment1.getTotal());
                            returnEquipmentDetail.setSn(cbsDeliverEquipment1.getSn());
                            returnEquipmentDetail.setDeliverEquipmentId(cbsDeliverEquipment1);
                            cbsReturnEquipmentDetailServiceI.save(returnEquipmentDetail);

                            //创建返件日志
                            CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                            cbsHandleLogEntity.setBusinessId(returnEquipment.getId());
                            cbsHandleLogEntity.setLogType(4);
                            cbsHandleLogEntity.setDescription("创建返件申请单");
                            cbsHandleLogEntity.setCreateName(user.getRealName());
                            cbsHandleLogEntity.setCreateBy(user.getUserName());
                            systemService.saveOrUpdate(cbsHandleLogEntity);
                        }
                    }
                }
                //设置备件类型
                if (equipmentTypeId != null) {
                    zyEquipmentType = zyEquipmentTypeService.singleResult("from ZyEquipmentTypeEntity where id='" + equipmentTypeId + "'");
                }

                if (zyEquipmentType != null) {
                    cbsDeliverEquipment.setTypeId(zyEquipmentType);
                    cbsDeliverEquipment.setTypeDes(zyEquipmentType.getTypeDesc());
                }

                //设置备件号
                if (itemId != null) {
                    ZyEsItemEntity zyEsItem = systemService.singleResult("from ZyEsItemEntity where id='" + itemId + "'");
                    System.out.println("zyEsItem:" + zyEsItem);
                    if (zyEsItem != null) {
                        cbsDeliverEquipment.setItem(zyEsItem.getItem());
                        cbsDeliverEquipment.setItemId(zyEsItem);
                    }
                }

                cbsDeliverEquipment.setMemo(memo);

                cbsDeliverEquipment.setIsReturn(Integer.valueOf(isReturn));
                cbsDeliverEquipment.setApplyLayer(Integer.valueOf(applyLayer));
                cbsDeliverEquipment.setTotal(1);
                cbsDeliverEquipment.setSn(sn);
                cbsDeliverEquipment.setApplyReason(applyReason);
                cbsDeliverEquipment.setUpdateDate(new Date());
                cbsDeliverEquipmentService.saveOrUpdate(cbsDeliverEquipment);

                //如果备件需要返件，创建返件任务
                if (cbsDeliverEquipment.getIsReturn() == 2) {
                    //组装返件单号FH+YYYYMMDD+001(增长)
                    Date date = new Date();
                    DateFormat format = new SimpleDateFormat("YYYYMMdd");
                    String time = format.format(date);
                    System.out.println(time);
                    StringBuffer buffer = new StringBuffer();
                    buffer.append("FJ");
                    buffer.append(time);
                    List<Object[]> returnEquipmentList = systemService.findListbySql("select * from cbs_return_equipment where to_days(create_date) = to_days(now()) ORDER BY `code` desc;");
                    CbsReturnEquipmentEntity returnEquipment = new CbsReturnEquipmentEntity();
                    CbsReturnEquipmentDetailEntity returnEquipmentDetail = new CbsReturnEquipmentDetailEntity();
                    returnEquipment.setSrCode(cbsdeliver.getSrCode());
                    returnEquipment.setSoCode(cbsdeliver.getSoCode());
                    returnEquipment.setDeliverCode(cbsdeliver.getCode());
                    returnEquipment.setCrCode(cbsdeliver.getCrCode());
                    returnEquipment.setEquipmentApplyId(cbsdeliver.getEquipmentApplyId());
                    returnEquipment.setStatus(StaticValue.RETURN_STATUS_Log_Type_1);
                    returnEquipment.setLogistics(cbsdeliver.getReturnLogistics());
                    returnEquipment.setLogisticsCode(cbsDeliverEquipment.getLogisticsNumber());
                    cbsReturnEquipmentServiceI.save(returnEquipment);

                    if (returnEquipmentList.size() == 0) {
                        buffer.append("001");
                        String s = buffer.toString();
                        returnEquipment.setCode(s);
                        cbsReturnEquipmentServiceI.save(returnEquipment);
                    } else {
                        String o = (String) returnEquipmentList.get(0)[1];
                        String s = o.substring(10, 13);
                        int l = Integer.parseInt(s);
                        l++;
                        if (l <= 9) {
                            buffer.append("00" + i);
                        } else if (l >= 10 && l < 100) {
                            buffer.append("0" + l);
                        } else {
                            buffer.append("" + l);
                        }
                        String string = buffer.toString();
                        returnEquipment.setCode(string);
                        cbsReturnEquipmentServiceI.save(returnEquipment);
                    }
                    returnEquipmentDetail.setReturnEquipmentId(returnEquipment);
                    returnEquipmentDetail.setTypeId(cbsDeliverEquipment.getTypeId());
                    returnEquipmentDetail.setTypeDes(cbsDeliverEquipment.getTypeDes());
                    returnEquipmentDetail.setItemId(cbsDeliverEquipment.getItemId());
                    returnEquipmentDetail.setItem(cbsDeliverEquipment.getItem());
                    returnEquipmentDetail.setItemTotal(cbsDeliverEquipment.getTotal());
                    returnEquipmentDetail.setSn(cbsDeliverEquipment.getSn());
                    returnEquipmentDetail.setDeliverEquipmentId(cbsDeliverEquipment);
                    cbsReturnEquipmentDetailServiceI.save(returnEquipmentDetail);

                    //创建返件日志
                    CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                    cbsHandleLogEntity.setBusinessId(returnEquipment.getId());
                    cbsHandleLogEntity.setLogType(4);
                    cbsHandleLogEntity.setDescription("创建返件申请单");
                    cbsHandleLogEntity.setCreateName(user.getRealName());
                    cbsHandleLogEntity.setCreateBy(user.getUserName());
                    systemService.saveOrUpdate(cbsHandleLogEntity);
                }
            }
            //记录发货单操作日志
            cbsDelinerService.addDeliverLog(user.getRealName() + "操作发货", cbsdeliver.getId(), 2);
        } catch (Exception e) {
            e.printStackTrace();
            message = "发货失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /*
     *取消发货
     */
    @RequestMapping(params = "removeDeliver")
    @ResponseBody
    public AjaxJson removeDeliver(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            j = cbsDelinerService.removeDeliver(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
        return j;
    }


    /**
     * 删除发货单信息
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsDelinerEntity cbsDeliner, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        System.out.println("id:" + cbsDeliner.getId());
        cbsDeliner = systemService.getEntity(CbsDelinerEntity.class, cbsDeliner.getId());
        message = "发货单信息删除成功";
        try {
            List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + cbsDeliner.getId() + "'");
            for (CbsDeliverEquipmentEntity cde : deliverEquipmentList) {
                systemService.delete(cde);
            }
            cbsDelinerService.delete(cbsDeliner);
            //添加进操作日志
            //获取登录的用户信息
            TSUser user = ResourceUtil.getSessionUserName();
            cbsDelinerService.addDeliverLog(user.getRealName() + "删除了发货单", cbsDeliner.getId(), 1);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "发货单信息删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除发货单信息
     *
     * @return
     */
    @RequestMapping(params = "deleteALLSelect")
    @ResponseBody
    public AjaxJson doBatchDel(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();

        String ids = request.getParameter("ids");
        System.out.println("ids:" + ids);
        JSONArray json = JSONArray.fromObject(ids);

        message = "发货单信息删除成功";
        try {
            for (int i = 0; i < json.size(); i++) {
                System.out.println("json:" + json.get(i));
                String id = (String) json.get(i);
                CbsDelinerEntity cbsDeliner = systemService.getEntity(CbsDelinerEntity.class, id);

                List<CbsDeliverEquipmentEntity> deliverEquipmentList = systemService.findHql("from CbsDeliverEquipmentEntity where deliverId.id='" + id + "'");
                for (CbsDeliverEquipmentEntity cde : deliverEquipmentList) {
                    systemService.delete(cde);
                }
                cbsDelinerService.delete(cbsDeliner);
                //添加进操作日志
                //获取登录的用户信息
                TSUser user = ResourceUtil.getSessionUserName();
                cbsDelinerService.addDeliverLog(user.getRealName() + "删除了发货单", cbsDeliner.getId(), 1);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "发货单信息删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbs_deliver/cbsDelinerUpload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(CbsDelinerEntity cbsDeliner, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
        TSUser user = ResourceUtil.getSessionUserName();
        CriteriaQuery cq = new CriteriaQuery(CbsDelinerEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsDeliner, request.getParameterMap());
        List<CbsDelinerEntity> cbsDeliners = this.cbsDelinerService.getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "发货单信息");
        modelMap.put(NormalExcelConstants.CLASS, CbsDelinerEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("发货单信息列表", "导出人:" + ResourceUtil.getSessionUserName().getRealName(),
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, cbsDeliners);
        systemService.addLog(user.getRealName() + "导出" + cbsDeliners.size() + "条发货单记录", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    @RequestMapping(params = "exportXls1")
    public void exportXls1(HttpServletRequest request, HttpServletResponse response) {
        TSUser user = ResourceUtil.getSessionUserName();
        systemService.addLog(user.getRealName() + "导出:发货单记录", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);

        cbsDelinerService.exportDeliverList(request, response);

    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsDelinerEntity cbsDeliner, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(TemplateExcelConstants.FILE_NAME, "发货单信息");
        modelMap.put(TemplateExcelConstants.PARAMS, new TemplateExportParams("Excel模板地址"));
        modelMap.put(TemplateExcelConstants.MAP_DATA, null);
        modelMap.put(TemplateExcelConstants.CLASS, CbsDelinerEntity.class);
        modelMap.put(TemplateExcelConstants.LIST_DATA, null);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CbsDelinerEntity> listCbsDelinerEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(), CbsDelinerEntity.class, params);
                for (CbsDelinerEntity cbsDeliner : listCbsDelinerEntitys) {
                    cbsDelinerService.save(cbsDeliner);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;

    }

    /*
     * 查看完工报告跳转
     * */
    @RequestMapping(params = "jumpPage", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson jumpPage(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String cbsId = request.getParameter("id");
        List<String> cbsIdList = systemService.findListbySql("select id from cbs_scene_check_report where service_id='" + cbsId + "'");
        if (cbsIdList.size() != 0) {
            j.setMsg("type-yj");
            return j;
        }
        List<String> idList = systemService.findListbySql("select id from cbs_engine_scene_check_report where service_id='" + cbsId + "'");
        if (idList.size() != 0) {
            j.setMsg("type-yqfx");
            return j;
        }
        j.setMsg("请先填写相应完工单");
        return j;
    }

    /*
     * 判断服务单服务类型
     * */
    @RequestMapping(params = "judgeService", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson judgeService(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String cbsId = request.getParameter("id");
        CbsServiceEntity entity = systemService.get(CbsServiceEntity.class, cbsId);
        List<String> cbsIdList = systemService.findListbySql("select id from cbs_scene_check_report where service_id='" + cbsId + "'");
        if (cbsIdList.size() != 0) {
            j.setMsg("type-yj");
            return j;
        }
        List<String> idList = systemService.findListbySql("select id from cbs_engine_scene_check_report where service_id='" + cbsId + "'");
        if (idList.size() != 0) {
            j.setMsg("type-yqfx");
            return j;
        }
        j.setSuccess(false);
        j.setObj(entity.getCode());
        return j;
    }


    //当前日期转化为MMdd字符转
    public String getDateStr(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("MMdd");
        String dateStr = df.format(date);
        return dateStr;
    }


    //判断发货对应的返件单但是否还有返件，如果没有则取消该返件
    public void checkeCountByDeliver(String deliverCode, TSUser user) {
        List<CbsReturnEquipmentEntity> reList = systemService.findHql("from CbsReturnEquipmentEntity where deliverCode='" + deliverCode + "'");
        if (reList != null && reList.size() > 0) {
            for (CbsReturnEquipmentEntity re : reList) {
                List<Map<String, Object>> rdIds = systemService.findForJdbc("select * from cbs_return_equipment_detail where return_equipment_id ='" + re.getId() + "'");
                if (rdIds == null || rdIds.size() <= 0) {
                    re.setStatus("5");
                    systemService.saveOrUpdate(re);

                    //创建返件日志
                    CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                    cbsHandleLogEntity.setBusinessId(re.getId());
                    cbsHandleLogEntity.setLogType(4);
                    cbsHandleLogEntity.setDescription("创建返件申请单");
                    cbsHandleLogEntity.setCreateName(user.getRealName());
                    cbsHandleLogEntity.setCreateBy(user.getUserName());
                    systemService.saveOrUpdate(cbsHandleLogEntity);
                }
            }
        }
    }


    //根据返件获取返件单
    public CbsReturnEquipmentEntity getReturnByDetail(String detailId) {
        CbsReturnEquipmentEntity returnEquipment = null;
        if (detailId != null && !detailId.equals("")) {
            CbsReturnEquipmentDetailEntity returnDetail = systemService.get(CbsReturnEquipmentDetailEntity.class, detailId);
            if (returnDetail != null && returnDetail.getReturnEquipmentId() != null && !returnDetail.getReturnEquipmentId().equals("")) {
                returnEquipment = systemService.get(CbsReturnEquipmentEntity.class, returnDetail.getReturnEquipmentId());
            }
        }

        return returnEquipment;
    }


    //判断返件单中是否有返件，没有则取消返件
    public void checkeReturnCount(CbsReturnEquipmentEntity returnEquipment, TSUser user) {
        if (returnEquipment != null) {
            List<Map<String, Object>> rdIds = systemService.findForJdbc("select * from cbs_return_equipment_detail where return_equipment_id ='" + returnEquipment.getId() + "'");
            if (rdIds == null || rdIds.size() <= 0) {
                returnEquipment.setStatus("5");
                systemService.saveOrUpdate(returnEquipment);

                //创建返件日志
                CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                cbsHandleLogEntity.setBusinessId(returnEquipment.getId());
                cbsHandleLogEntity.setLogType(4);
                cbsHandleLogEntity.setDescription("CSA取消返件");
                cbsHandleLogEntity.setCreateName(user.getRealName());
                cbsHandleLogEntity.setCreateBy(user.getUserName());
                systemService.saveOrUpdate(cbsHandleLogEntity);
            }
        }
    }



    @RequestMapping(params = "toCbsDeliverReport")
    public ModelAndView toCbsDeliverReport(HttpServletRequest request) {

        return new ModelAndView("com/zybk/cbs_deliver/cbsDeliverReport");
    }

    @RequestMapping(params = "toCbsDeliverReportAging")
    public ModelAndView toCbsDeliverReportAging(HttpServletRequest request) {
        String hql = "from TSType where TSTypegroup.typegroupcode='Deliver_Type'";
        List<TSType> tSTypeList = systemService.findHql(hql);
        request.setAttribute("tSTypeList", tSTypeList);
        List<TSDepart> tsDeparts = systemService.findHql("from TSDepart where orgType='logistics' and logicDelete = '0'");
        request.setAttribute("tsDeparts", tsDeparts);
        return new ModelAndView("com/zybk/cbs_deliver/cbsDeliverAgingReport");
    }

    @ResponseBody
    @RequestMapping(params = "loadDataAging")
    public AjaxJson loadDataAging(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        String logistics = request.getParameter("logistics");
        String sendType = request.getParameter("sendType");
        String month = request.getParameter("month");
        String week = request.getParameter("week");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        List<Map<String, Object>> deliverAging = cbsDelinerService.getDeliverAging(logistics, sendType, month, week, startTime, endTime);
        map.put("deliverAging", deliverAging);
        ajaxJson.setAttributes(map);
        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "getCharData")
    public List<Highchart> getCharData(HttpServletRequest request) {
        String logistics = request.getParameter("logistics");
        String sendType = request.getParameter("sendType");
        String month = request.getParameter("month");
        String week = request.getParameter("week");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        return cbsDelinerService.getCharData(logistics, sendType, month, week, startTime, endTime);
    }

    @RequestMapping(params = "toSelectReportJsp")
    public ModelAndView toSelectReportJsp(HttpServletRequest request, HttpSession session) {
        String type = request.getParameter("type");
        String name = request.getParameter("name");
        session.setAttribute("typeReport", type);
        session.setAttribute("logicisName", name);
        return new ModelAndView("com/zybk/cbs_deliver/selectDelinerReportList");
    }

    @RequestMapping(params = "datagridReport")
    public void datagridReport(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid, HttpSession session) {
        Map param = new HashMap<>();
        String typeReport = (String) session.getAttribute("typeReport");
        String logicisName = (String) session.getAttribute("logicisName");
        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                    }
                }
            }
        }

        if (StringUtil.isNotEmpty(typeReport)) {
            if (typeReport.equals("total")) {
                param.put("total", typeReport);
            }
            if (typeReport.equals("lessOrEqTwf")) {
                param.put("lessOrEqTwf", typeReport);
            }
            if (typeReport.equals("lessOrEqFoEg")) {
                param.put("lessOrEqFoEg", typeReport);
            }
            if (typeReport.equals("lessOrEqSenTw")) {
                param.put("lessOrEqSenTw", typeReport);
            }
            if (typeReport.equals("biggerOrEqSenTw")) {
                param.put("biggerOrEqSenTw", typeReport);
            }
            if (typeReport.equals("waying")) {
                param.put("waying", typeReport);
            }
        }


        if (!StringUtil.isEmpty(logicisName)) {
            param.put("logicisName", logicisName);
        }
        wiseCoreService.selectDataGrid("selectDeliverByReport", param, dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }

    @ResponseBody
    @RequestMapping(params = "toStatisticalShipment")
    public List<Highchart> toStatisticalShipment(HttpServletRequest request) throws Exception {
        String type = request.getParameter("type");
        String slaType = request.getParameter("slaType");
        String month = request.getParameter("month");
        String week = request.getParameter("week");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String temp = request.getParameter("temp");
        List<Highchart> highchartList = new ArrayList<>();
        /**
         * update by X on 20181112 当只选择发货时间范围查询时 或者 三个条件都是空的情况 采用单独的查询方式（后期 如果 周报和 月报查询 单独区分开来 就只调用这个方法就可以）
         */
        if((StringUtil.isNotEmpty(startTime) && StringUtil.isNotEmpty(endTime))
                || (StringUtil.isEmpty(startTime) && StringUtil.isEmpty(endTime) && StringUtil.isEmpty(month) && StringUtil.isEmpty(week))){
            highchartList = cbsDelinerService.getDeliverData(type, slaType, startTime, endTime);
        }
        /**
         * -- END -- update by X on 20181112 当只选择发货时间范围查询时 或者 三个条件都是空的情况 采用单独的查询方式（后期 如果 周报和 月报查询 单独区分开来 就只调用这个方法就可以） --END
         */
        else {
            boolean f = false;
            if (StringUtil.isNotEmpty(temp)) {
                f = true;
            }
            List<TSDepart> tsDepartList = systemService.findHql("from TSDepart where orgType ='logistics'");
            TSDepart tsDepart = new TSDepart();
            TSDepart tsDepart1 = new TSDepart();
            tsDepart.setDepartname("Target");
            tsDepart1.setDepartname("Combine");
            tsDepartList.add(tsDepart);
            tsDepartList.add(tsDepart1);
            List<Highchart> highcharts = null;
            for (int i = 0; i < tsDepartList.size(); i++) {
                highcharts = cbsDelinerService.toStatisticalShipment(tsDepartList.get(i).getDepartname(), slaType, type, month, week, startTime, endTime, f);
                highchartList.addAll(highcharts);
            }
        }
        return highchartList;
    }

    @ResponseBody
    @RequestMapping(params = "getSl2Percentage")
    public List<Highchart> getSl2Percentage(HttpServletRequest request) throws Exception {
        String type = request.getParameter("type");
        String slaType = request.getParameter("slaType");
        String month = request.getParameter("month");
        String week = request.getParameter("week");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String temp = request.getParameter("temp");
        List<Highchart> highchartList = new ArrayList<>();

        /**
         * update by X on 20181112 当只选择发货时间范围查询时 或者 三个条件都是空的情况 采用单独的查询方式（后期 如果 周报和 月报查询 单独区分开来 就只调用这个方法就可以）
         */
        if((StringUtil.isNotEmpty(startTime) && StringUtil.isNotEmpty(endTime))
            || (StringUtil.isEmpty(startTime) && StringUtil.isEmpty(endTime) && StringUtil.isEmpty(month) && StringUtil.isEmpty(week))){
            highchartList = cbsDelinerService.getDeliverData(type, slaType, startTime, endTime);
        }
        /**
         * -- END -- update by X on 20181112 当只选择发货时间范围查询时 或者 三个条件都是空的情况 采用单独的查询方式（后期 如果 周报和 月报查询 单独区分开来 就只调用这个方法就可以） --END
         */

        else{
            boolean f = false;
            if (StringUtil.isNotEmpty(temp)) {
                f = true;
            }
            List<TSDepart> tsDepartList = systemService.findHql("from TSDepart where orgType ='logistics'");
            TSDepart tsDepart = new TSDepart();
            TSDepart tsDepart1 = new TSDepart();
            tsDepart.setDepartname("Target");
            tsDepart1.setDepartname("Combine");
            tsDepartList.add(tsDepart);
            tsDepartList.add(tsDepart1);
            List<Highchart> highcharts = null;
            for (int i = 0; i < tsDepartList.size(); i++) {
                highcharts = cbsDelinerService.getSl2Percentage(tsDepartList.get(i).getDepartname(), slaType, month, week, startTime, endTime, f);
                highchartList.addAll(highcharts);
            }
        }

        return highchartList;
    }

    @RequestMapping(params = "exReportCbsDeliver")
    @ResponseBody
    public void exReportCbsDeliver(HttpServletRequest request, HttpServletResponse response) {
        cbsDelinerService.exportCbsDeliverReport(request, response);
    }

    @RequestMapping(params = "exportXlsForLogistics")
    public void exportXlsForLogistics(HttpServletRequest request, HttpServletResponse response) {
        TSUser user = ResourceUtil.getSessionUserName();
        systemService.addLog(user.getRealName() + "导出:发货单记录", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);

        cbsDelinerService.exportDeliverListForLogistics(request, response);
    }
}


